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

2023-10-27

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

For example:

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?

解决方案

From the Python documentation itself, you can use max:

>>> mylist = ['123','123456','1234']

>>> print max(mylist, key=len)

123456

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python 列表中最长字符串,Python选择列表中最长字符串的最有效方法? 的相关文章

随机推荐