【问题标题】:Multiply the first element of a list by a given number and calculate a cumulative product of the resulting list将列表的第一个元素乘以给定的数字并计算结果列表的累积乘积
【发布时间】:2019-07-18 08:20:42
【问题描述】:

我有以下清单:

l = [1, 2, 3, 4, 5, 6]

我想将第一个元素乘以9(1*9)=9,然后将所有连续的项目乘以前一个乘法的结果。请参阅以下输出:

[9, 18, 54, 216, 1080, 6480]

【问题讨论】:

标签: python list accumulate


【解决方案1】:

您可以更新列表中的第一项,并使用itertools.accumulateoperator.mul 来获取其值的累积乘积:

from operator import mul
from itertools import accumulate

l = [1, 2, 3, 4, 5, 6]

l[0]*=9
list(accumulate(l, mul))
# [9, 18, 54, 216, 1080, 6480]

【讨论】:

    猜你喜欢
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 2017-03-02
    • 2021-12-16
    • 1970-01-01
    • 2020-07-18
    • 2011-12-13
    相关资源
    最近更新 更多