Python中选择列表中最长字符串的最有效方法?
我有一个长度不固定的列表,想找个方法来检查当前正在评估的列表项是否是列表中最长的字符串。而我使用的是Python 2.6.1。
举个例子:
mylist = ['abc','abcdef','abcd']
for each in mylist:
if condition1:
do_something()
elif ___________________: #else if each is the longest string contained in mylist:
do_something_else()
肯定有一种简单又优雅的列表推导式我没有想到,对吧?
7 个回答
8
如果有多个最长的字符串,比如'12'和'01',应该怎么处理呢?
试着找出最长的元素
max_length,longest_element = max([(len(x),x) for x in ('a','b','aa')])
然后用普通的foreach循环
for st in mylist:
if len(st)==max_length:...
14
def longestWord(some_list):
count = 0 #You set the count to 0
for i in some_list: # Go through the whole list
if len(i) > count: #Checking for the longest word(string)
count = len(i)
word = i
return ("the longest string is " + word)
或者简单得多:
max(some_list , key = len)