繁体   English   中英

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

[英]Searching a list for the longest string

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

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

我正在尝试做这样的事情:

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

因此,它是要遍历列表并将每个项目与整数max_l进行比较。 一旦找到该列表项,就意味着要打印它。 虽然没有。 我究竟做错了什么?

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

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

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

max一个'key'参数,您可以为其分配一个函数(在本例中为len ,另一个内置函数),该函数将应用于myList中的每个项目。

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

max文档字符串:

max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.

len docstring中:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM