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()

肯定有一个简单的列表理解,它是我忽略的简短而优雅的吗?

原文由 user104997 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 330
2 个回答

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

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

原文由 Paolo Bergantino 发布,翻译遵循 CC BY-SA 2.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)

或者更容易:

 max(some_list , key = len)

原文由 Саво Вуковић 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题