[英]Append cumulative list of lists python
I am trying to extend a list of lists in a commulative way like this:我正在尝试以这样的交互方式扩展列表列表:
# Consider the following list of lists
l_Of_l = [ [1], [2], [3], [4], [5], [6], [7]]
Desired result is:期望的结果是:
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]]
So basically the size of the list remains the same after extending commulatively.所以基本上列表的大小在交互扩展后保持不变。
Edit:编辑:
Here is what I did initially:这是我最初所做的:
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]))
But then the result was:但后来的结果是:
[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]
Does anyone know how to achieve this in the correct way?有谁知道如何以正确的方式实现这一目标?
Use accumulate from itertools:使用 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]]
One way to do this without itertools is to use Python's sum
function to concatenate lists.在没有 itertools 的情况下执行此操作的一种方法是使用 Python 的
sum
function 来连接列表。
>>> L = [ [1], [2], [3], [4], [5], [6], [7] ]
>>> L_extend = [ sum(L[0:i+1], []) for i in range(len(L)) ]
You want a cumulative sum, just with lists.你想要一个累加和,只是列表。
itertools.accumulate
can do this. 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]]
You can also create a simple list comprehension:您还可以创建一个简单的列表理解:
>>> 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]]
lol = [ [1], [2], [3], [4], [5], [6], [7] ]
lol_test = [[*range(1, i+2)]for i in range(len(lol))]
print(lol_test)
I came up with a solution similar to Bill M, just a small difference.我想出了一个类似于 Bill M 的解决方案,只是有一点不同。 I am just a novice learning python.
我只是一个新手学习python。
And it worked with the same output: [[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]]它与相同的 output 一起工作:[[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]]
Yet another method using list(range()) in list comprehension method.在列表理解方法中使用 list(range()) 的另一种方法。
lol = [ [1], [2], [3], [4], [5], [6], [7] ]
lol_test2 = [list(range(1, i+2))for i in range(len(lol))]
print(lol_test2)
Output: [[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]] Output: [[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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.