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

use*_*997 220 python list-comprehension list

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

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

谢谢!

Pao*_*ino 562

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

>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456
Run Code Online (Sandbox Code Playgroud)

  • 它只返回第一个最长的字符串:例如,`print(max(["this","does","work"],key = len))`只返回""this"`而不是返回所有最长的字符串字符串. (11认同)
  • 要获得每个最大元素,在线性时间内,你必须做`m = max(map(len,xs)); [x代表x中的x,如果len(x)== m]`.我不认为它可以在一行中很好地完成. (4认同)
  • 不适用于 Python 2.4。见[这篇文章](http://bytes.com/topic/python/answers/37337-key-argument-max#post140122)和[这篇文章](http://bytes.com/topic/python/answers/ 37337-key-argument-max#post140143) 用于在 2.4 下实现的代码。 (2认同)

Ela*_*ich 6

如果最长的字符串超过1个(应该考虑'12'和'01'),该怎么办?

尝试获得最长的元素

max_length,longest_element = max([(len(x),x) for x in ('a','b','aa')])
Run Code Online (Sandbox Code Playgroud)

然后定期进行foreach

for st in mylist:
    if len(st)==max_length:...
Run Code Online (Sandbox Code Playgroud)


小智 5

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)
Run Code Online (Sandbox Code Playgroud)

或更容易:

max(some_list , key = len)
Run Code Online (Sandbox Code Playgroud)