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

2024-04-25 09:27:04 发布

您现在位置: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()

当然有一个简单的列表理解,我忽略了它的简短和优雅


Tags: 方法字符串in列表forifdoelse
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)

Python documentation本身,可以使用^{}

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

如果有超过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:...

相关问题 更多 >