繁体   English   中英

Python在子列表中查找列表长度

[英]Python find list lengths in a sublist

我试图找出如何获得特定列表中的每个列表的长度。 例如:

a = []
a.append([])
a[0].append([1,2,3,4,5])
a[0].append([1,2,3,4])
a[0].append([1,2,3])

我想运行一个命令:

len(a[0][:]) 

这将输出我想要的答案,这是一个长度列表[5,4,3]。 这个命令显然不起作用,我试过的其他一些也没有用。 请帮忙!

[len(x) for x in a[0]]

>>> a = []
>>> a.append([])
>>> a[0].append([1,2,3,4,5])
>>> a[0].append([1,2,3,4])
>>> a[0].append([1,2,3])
>>> [len(x) for x in a[0]]
[5, 4, 3]

map(len, a[0])

[len(x) for x in a[0]]

这称为列表理解 (单击以获取更多信息和说明)。

[len(l) for l in a[0]]
def lens(listoflists):
  return [len(x) for x in listoflists]

现在,只需要调用lens(a[0])而不是你想要的len(a[0][:]) (如果你坚持的话,你可以添加多余的[:] ,但这只是为了一个无用的目的而做一个副本 - 浪费不可;-)。

使用通常的“老派”方式

t=[]
for item in a[0]:
    t.append(len(item))
print t

Matthew的答案在Python 3中不起作用。以下内容适用于Python 2和Python 3

list(map(len, a[0]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM