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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2031846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:37:21  来源:igfitidea点击:

Python find list lengths in a sublist

pythonlist

提问by JBWhitmore

I am trying to find out how to get the length of every list that is held within a particular list. For example:

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

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

I'd like to run a command like:

我想运行如下命令:

len(a[0][:]) 

which would output the answer I want which is a list of the lengths [5,4,3]. That command obviously does not work, and neither do a few others that I've tried. Please help!

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

回答by sberry

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

[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]

回答by Matthew Iselin

map(len, a[0])

map(len, a[0])

回答by John Machin

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

回答by T. Stone

This is known as List comprehension(click for more info and a description).

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

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

回答by Alex Martelli

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

now, just call lens(a[0])instead of your desired len(a[0][:])(you can, if you insist, add that redundant [:], but that's just doing a copy for no purpose whatsoever -- waste not, want not;-).

现在,只需调用lens(a[0])而不是你想要的len(a[0][:])(如果你坚持,你可以添加那个多余的[:],但这只是无缘无故地复制——不要浪费,不要;-)。

回答by ghostdog74

using the usual "old school" way

使用通常的“老派”方式

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

回答by divenex

Matthew's answer does not work in Python 3. The following one works in both Python 2 and Python 3

马修的答案在 Python 3 中不起作用。以下一个在 Python 2 和 Python 3 中都有效

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

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