Python 在列表中选择最长字符串的最有效方法? [英] Python's most efficient way to choose longest string in list?

查看:58
本文介绍了Python 在列表中选择最长字符串的最有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个长度可变的列表,我正在尝试寻找一种方法来测试当前正在评估的列表项是否是列表中包含的最长字符串.我使用的是 Python 2.6.1

例如:

mylist = ['abc','abcdef','abcd']对于 mylist 中的每个:如果条件 1:做点什么()elif ____________________: #else 如果每个都是 mylist 中包含的最长字符串:do_something_else()

肯定有一个我忽略的简短而优雅的简单列表推导式吗?

解决方案

来自 Python 文档 本身,你可以使用 max:

<预><代码>>>>mylist = ['123','123456','1234']>>>打印最大值(mylist,key=len)123456

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

这篇关于Python 在列表中选择最长字符串的最有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆