Python在列表中选择最长字符串的最有效方法? [英] Python's most efficient way to choose longest string in list?
本文介绍了Python在列表中选择最长字符串的最有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个可变长度的列表,正在尝试寻找一种方法来测试当前正在评估的列表项是否为列表中包含的最长字符串.我正在使用Python 2.6.1
I have a list of variable length and am trying to find a way to test if the list item currently being evaluated is the longest string contained in the list. And I am using 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()
肯定有一个简单的列表理解功能,我忽略了它的简短和优雅吗?
Surely there's a simple list comprehension that's short and elegant that I'm overlooking?
推荐答案
来自 max
:
From the Python documentation itself, you can use max
:
>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456
这篇关于Python在列表中选择最长字符串的最有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文