附加列表的累积列表 python
Append cumulative list of lists python
我正在尝试以这样的交换方式扩展列表列表:
# 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]
有谁知道如何以正确的方式实现这一点?
使用 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]]
你想要一个累加和,只需要列表。 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]]
您还可以创建一个简单的列表理解:
>>> 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]]
不使用 itertools 的一种方法是使用 Python 的 sum
函数来连接列表。
>>> L = [ [1], [2], [3], [4], [5], [6], [7] ]
>>> L_extend = [ sum(L[0:i+1], []) for i in range(len(L)) ]
我正在尝试以这样的交换方式扩展列表列表:
# 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]
有谁知道如何以正确的方式实现这一点?
使用 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]]
你想要一个累加和,只需要列表。 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]]
您还可以创建一个简单的列表理解:
>>> 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]]
不使用 itertools 的一种方法是使用 Python 的 sum
函数来连接列表。
>>> L = [ [1], [2], [3], [4], [5], [6], [7] ]
>>> L_extend = [ sum(L[0:i+1], []) for i in range(len(L)) ]