gpt4 book ai didi

python - 从现有列表创建新的列表累积列表

转载 作者:行者123 更新时间:2023-11-28 20:30:03 25 4
gpt4 key购买 nike

我正在尝试使用 Python 构建一个累积列表列表,其中列表中的每个元素都按列表中前一个元素的值数增长。下面的代码示例应该更清楚。

my_list = [[1,2,3],[4,5,6],[7,8,9]]
list_new = []
final_list = []

for i in my_list:
list_new += i
final_list.append(list_new)

我想得到的结果是

[
[1,2,3]
, [1,2,3,4,5,6]
, [1,2,3,4,5,6,7,8,9]
]

但是我得到了

[
[1,2,3,4,5,6,7,8,9]
, [1,2,3,4,5,6,7,8,9]
, [1,2,3,4,5,6,7,8,9]
]

非常感谢您的帮助!

最佳答案

或者,使用 itertools.accumulate :

>>> my_list = [[1,2,3],[4,5,6],[7,8,9]]
>>> list(itertools.accumulate(my_list))
[[1, 2, 3], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7, 8, 9]]

关于python - 从现有列表创建新的列表累积列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58820753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com