- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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/
我对编程非常陌生(所以我提前道歉),并且我无法弄清楚如何创建一个 for 循环来执行以下操作: 我要求用户输入两个变量(我将它们称为 x 和 y),然后我计算 x/y = z。我想提出这个两个变量输入
我正在尝试对 vector 使用累加函数 vector A; double B = 0; A.reserve(100); for(itr = 0; itr < 210; itr++) { t
如果我想累积 std::vector 的绝对值,我可以使用 lambda 来计算绝对值并将其添加到 std::accumulate #include int main (){ std::ve
所以我需要使用 accumulate 对 vector 中的一些 double 值求和,其中我的 VECTOR 实际上是指向对象的指针。 现在,当我将 accumulate 与 int 一起用于 in
假设我有一个 (None, 2)-shape 张量 indices 和 (None,)-shape 张量 values。这些实际行号和值将在运行时确定。 我想设置一个 4x5 张量 t,索引的每个元素
我有一小部分固定节点: , , , .每个节点的值可以是 1 或 0。此外,每个节点的权重分别为:1、2、3、4。不使用节点属性。如何使用 XSLT 1.0 将每个节点的值乘以其权重相加?示例:
目前我在下面有一个数据集,如果 ColA 为 0,我尝试累加该值,而如果 ColA 再次为 1,则将值重置为 0(再次重新开始计数)。 ColA 1 0 1
我是一名优秀的程序员,十分优秀!