gpt4 book ai didi

python - 有没有办法在Python中从右到左累加?

转载 作者:行者123 更新时间:2023-12-04 14:57:41 24 4
gpt4 key购买 nike

Python 已经有一个 itertools.accumulate 函数。然而,这个函数从左到右累加:

>>> list(itertools.accumulate([[x] for x in range(5)]))
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]

相反,我想从右到左累积,像这样:

>>> list(accumulate_from_right([[x] for x in range(5)]))
[[0, 1, 2, 3, 4], [1, 2, 3, 4], [2, 3, 4], [3, 4], [4]]

我当前的解决方案(仅适用于列表)非常低效且丑陋:

>>> list(x[::-1] for x in accumulate([y] for y in reversed(range(5))))[::-1]
[[0, 1, 2, 3, 4], [1, 2, 3, 4], [2, 3, 4], [3, 4], [4]]

从右到左累积列表的最佳方法是什么?

编辑:我使用范围作为示例。我希望能够将此方法应用于任何嵌套列表。

这是另一个不使用范围的例子:

>>> list(accumulate_from_right(['a', 'b', 'c']))
['abc', 'bc', 'c']

最佳答案

您只需对 accumulate_from_right 的输入进行一次传递:

def accumulate_from_right(vals):
return [vals[i:] for i in range(len(vals))]

print(accumulate_from_right(list(range(5))))
print(accumulate_from_right(['a', 'b', 'c']))

输出:

[[0, 1, 2, 3, 4], [1, 2, 3, 4], [2, 3, 4], [3, 4], [4]]
[['a', 'b', 'c'], ['b', 'c'], ['c']]

关于python - 有没有办法在Python中从右到左累加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67640815/

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