Python的最有效的方法来select列表中最长的string?

我有一个可变长度的列表,并试图find一种方法来testing当前正在评估的列表项是否是列表中包含的最长的string。 我正在使用Python 2.6.1

例如:

mylist = ['123','123456','1234'] for each in mylist: if condition1: do_something() elif ___________________: #else if each is the longest string contained in mylist: do_something_else() 

我是python品牌,我相信我只是有一个大脑放屁。 当然有一个简单的列表理解,短暂而优雅,我俯瞰?

谢谢!

从Python文档本身,你可以使用max

 >>> mylist = ['123','123456','1234'] >>> print max(mylist, key=len) 123456 

如果超过1个最长的string,会发生什么(想'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:... 

len(each) == max(len(x) for x in myList)或者each == max(myList, key=len)

要获得列表中最小或最大的项目,请使用内置的最小和最大函数:

 lo = min(L) hi = max(L) As with sort (see below), you can pass in a key function 

用于在比较之前映射列表项目:

 lo = min(L, key=int) hi = max(L, key=int) 

http://effbot.org/zone/python-list.htm

看起来像你可以使用最大值函数,如果你正确的映射string,并使用它作为比较。 我会build议只find一次尽pipe当然,而不是列表中的每个元素。

 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) 
 def LongestEntry(lstName): totalEntries = len(lstName) currentEntry = 0 longestLength = 0 while currentEntry < totalEntries: thisEntry = len(str(lstName[currentEntry])) if int(thisEntry) > int(longestLength): longestLength = thisEntry longestEntry = currentEntry currentEntry += 1 return longestLength