我正在尝试以一种类似的方式扩展列表列表:
# Consider the following list of lists
l_Of_l = [ [1], [2], [3], [4], [5], [6], [7]]
期望的结果是:
l_extended = [ [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7]]
因此,经过累加扩展后,列表的大小基本上保持不变。
编辑:
这是我最初所做的:
l_Of_l = [ [1], [2], [3], [4], [5], [6], [7]]
lista = []
for i in l_Of_l:
lista.extend(i)
print(list([i for i in lista]))
但是结果是:
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
有人知道如何以正确的方式实现这一目标吗?
答案 0 :(得分:4)
使用itertools中的累积值:
list(itertools.accumulate(l_Of_l))
Out:
[[1],
[1, 2],
[1, 2, 3],
[1, 2, 3, 4],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6, 7]]
答案 1 :(得分:2)
没有itertools的一种方法是使用Python的sum
函数来连接列表。
>>> L = [ [1], [2], [3], [4], [5], [6], [7] ]
>>> L_extend = [ sum(L[0:i+1], []) for i in range(len(L)) ]
答案 2 :(得分:1)
您只需要列表就可以求和。 itertools.accumulate
可以做到这一点。
>>> from itertools import accumulate
>>> lst = [[1], [2], [3], [4], [5], [6], [7]]
>>> list(accumulate(lst))
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7]]
答案 3 :(得分:1)
您还可以创建一个简单的列表理解:
>>> from operator import itemgetter
>>> l_Of_l = [[1], [2], [3], [4], [5], [6], [7]]
>>> [list(map(itemgetter(0), l_Of_l[:i+1])) for i in range(len(l_Of_l))]
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7]]