最长子列表的长度? [英] Length of the longest sublist?

查看:50
本文介绍了最长子列表的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
Python 在列表中选择最长字符串的最有效方法?

我有一个清单L

L = [[1,2,3],[5,7],[1,3],[77]]

我想返回最长子列表的长度而不需要遍历它们,在本例中为3,因为[1,2,3]是长度3,并且是四个子列表中最长的.我尝试了len(max(L)),但这不能满足我的要求.有什么方法可以做,还是循环是我唯一的方法?

I want to return the length of the longest sublist without needing to loop through them, in this case 3 because [1,2,3] is length 3 and it is the longest of the four sublists. I tried len(max(L)) but this doesn't do what I want. Any way to do this or is a loop my only way?

推荐答案

max(L,key = len)将为您提供最长的对象( [1,2,3] (在您的示例中)—要实际获取长度(如果这是您关心的全部),可以执行 len(max(L,key = len))有点丑-我把它分成两行.或者您可以使用 ecatamur 提供的版本.

max(L,key=len) will give you the object with the longest length ([1,2,3] in your example) -- To actually get the length (if that's all you care about), you can do len(max(L,key=len)) which is a bit ugly -- I'd break it up onto 2 lines. Or you can use the version supplied by ecatamur.

所有这些答案都有循环-在我的情况下,循环是隐式,这通常意味着它们将在优化的本机代码中执行.如果您考虑一下,不看每个元素怎么会知道最长的元素?

All of these answers have loops -- in my case, the loops are implicit which usually means they'll be executed in optimized native machine code. If you think about it, How could you know which element is the longest without looking at each one?

最后,请注意, key = function 并不是特定于 max 的功能.很多 python 内置函数 (max,min,sorted,itertools.groupby,...) 使用这个特定的关键字参数.绝对值得花一点时间来了解它的工作原理和通常的功能.

Finally, note that key=function isn't a feature that is specific to max. A lot of the python builtins (max,min,sorted,itertools.groupby,...) use this particular keyword argument. It's definitely worth investing a little time to understand how it works and what it typically does.

这篇关于最长子列表的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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