如果您想在列表中搜索最长的字符串,您可以使用内置的max() 函数:
myList = ['string', 'cat', 'mouse', 'gradient']
print max(myList, key=len)
'gradient'
max 接受一个“key”参数,您可以为其分配一个函数(在本例中为 len,另一个内置函数),该函数应用于 myList 中的每个项目。
在这种情况下,myList 中每个字符串的 len(string) 返回最大的结果(长度)是您最长的字符串,并由 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 文档字符串:
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']
现在使用最大值:
print max(user, key=len)
'Hello' # since 'Hello' and 'madam' are both of length 5, max just returns the first one