[英]Get all first element of tuples from list of lists of tuples in Python
[英]Get indices of the first element in a python list of lists
我有一个这样的列表:
[[21], [22, 1], [23, 2], [24, 1, 0, 4], [25, 2, 3]]
我想 append 到一个新列表中每个子列表的第一项的索引,同时计算所有子列表中的所有元素。 新列表的每个索引取决于每个子列表的长度。 我正在寻找的结果是这个:
[0、1、3、5、9]。
我不想使用 numpy 或任何其他库。 谢谢!
累加从零开始的长度:
L = [[21], [22, 1], [23, 2], [24, 1, 0, 4], [25, 2, 3]]
from itertools import accumulate
idx = [0,*accumulate(map(len,L[:-1]))]
print(idx) # [0, 1, 3, 5, 9]
你需要这样的东西:
l = [[21], [22, 1], [23, 2], [24, 1, 0, 4], [25, 2, 3]]
n = []
p = 0
for s1 in l:
n.append(p)
p += len(s1)
print(n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.