Python在列表中选择最长字符串的最有效方法是什么?

时间:2009-05-16 21:15:31

标签: python list list-comprehension

我有一个变量长度列表,我试图找到一种方法来测试当前正在评估的列表项是否是列表中包含的最长字符串。我正在使用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()

我是蟒蛇新手,我敢肯定我只是一个大脑放屁。当然有一个简单的列表理解,我忽略了它的简短和优雅?

谢谢!

6 个答案:

答案 0 :(得分:513)

Python documentation本身,您可以使用max

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

答案 1 :(得分:4)

如果有超过1个最长的字符串(想想'12'和'01')会发生什么?

尝试获取最长的元素

max_length,longest_element = max([(len(x),x) for x in ('a','b','aa')])

然后定期预约

for st in mylist:
    if len(st)==max_length:...

答案 2 :(得分:3)

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)

答案 3 :(得分:2)

  

要获取列表中最小或最大的项目,请使用内置的min和   最大功能:

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

如果您正确映射字符串并将其用作比较,您似乎可以使用max函数。我建议只找一次最大值,当然不是列表中的每个元素。

答案 4 :(得分:1)

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

答案 5 :(得分:1)

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