287

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

当然,我忽略了一个简短而优雅的简单列表理解?

4

6 回答 6

707

Python 文档本身,您可以使用max

>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456
于 2009-05-16T21:19:46.140 回答
9
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)
于 2016-12-14T23:26:45.433 回答
8

如果有超过 1 个最长的字符串(想想 '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:...
于 2009-05-16T21:22:37.817 回答
4

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

于 2009-05-16T21:20:36.993 回答
4

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

 lo = min(L)
 hi = max(L)  

与排序一样,您可以传入一个“键”参数,用于在比较列表项之前对其进行映射:

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

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

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

于 2009-05-16T21:20:49.180 回答
0
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
于 2011-10-21T23:21:47.587 回答