使用列表推导乘以整数列表

时间:2016-03-11 06:20:20

标签: python-2.7 list-comprehension

有没有办法用列表理解来做到这一点?

for i in range(0, len(x)):
    if i == 0:
        sum = x[i]
    else:
        sum = sum * x[i]

我试过这个:

[total for i in x if i == 0 total = x[i] else total = total * x[i]]

和此:

[total = x[i] if i == 0 else total = total * x[i] for i in x]

我看到有一种方法可以用enumerate来做,但我想知道是否有办法只使用列表理解在一行中完成它。我不是想解决问题,我只是好奇。

2 个答案:

答案 0 :(得分:2)

我认为你需要的是reduce,但不是列表理解。

from operator import mul
s = [1, 2, 3]
print reduce(mul, s, 1)

或使用列表理解:

class Mul(object):
    def __init__(self):
        self.product = 1
    def __call__(self, x):
        self.product *= x
        return self.product

s = [1, 2, 3, 4, 5]
m = Mul()
[m(x) for x in s]

答案 1 :(得分:1)

我要在前面添加#34;你不想这样做"。不完全是。但如果你这样做......

# whatever your input is
x = [1, 2, 3, 4, 5]

# set the initial total to 1, and wrap it in a list so we can modify it in an expression
total = [1]

# did I mention you shouldn't do this?
[total.__setitem__(0, xi * total.__getitem__(0)) for xi in x]

print total[0]
120