在列表中搜索最长的字符串

2024-04-26 10:30:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个当用户输入一个字符串时生成的列表:像这样。它将获取每个单词并将其附加到一个列表中。在

我有一个名为max_l的变量,它可以找到列表中最长字符串的长度。在

我正试着做这样的事情:

while max_l == len(mylist[x]):
    print(mylist[x])
    a=a+1

所以,它要遍历列表并将每个项与整数max_l进行比较,一旦找到该列表项,就要打印它。但是没有。我做错什么了?在


Tags: 字符串用户列表len整数单词事情max
1条回答
网友
1楼 · 发布于 2024-04-26 10:30:22

如果要在列表中搜索最长的字符串,可以使用内置的max()函数:

myList = ['string', 'cat', 'mouse', 'gradient']

print max(myList, key=len)
'gradient'

max接受一个“key”参数,您可以将一个应用于myList中每个项的函数(在本例中是len,另一个内置函数)。在

在这种情况下,myList中每个字符串的len(string)返回的最大结果(长度)是最长的字符串,并由max返回。在

来自max文档字符串:

^{pr2}$

来自len文档字符串:

len(object) -> integer

Return the number of items of a sequence or mapping.

根据用户输入生成列表:

针对你的评论,我想我会加上这一点。这是一种方法:

user = raw_input("Enter a string: ").split() # with python3.x you'd be using input instead of raw_input

Enter a string: Hello there sir and madam # user enters this string
print user
['Hello', 'there', 'sir', 'and', 'madam']

现在要使用max:

print max(user, key=len)
'Hello' # since 'Hello' and 'madam' are both of length 5, max just returns the first one

相关问题 更多 >