Python 2.7 使用列表理解将整数列表相乘
有没有办法通过列表理解来做到这一点Python 2.7 使用列表理解将整数列表相乘,python-2.7,list-comprehension,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
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
来完成,但我想知道是否有一种方法可以只使用列表理解在一行中完成。我不是想解决问题,我只是好奇 我想你需要的是减少,而不是列表理解
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]
我会在这之前加上“你不想这么做”。不,真的。但是如果你做了
# 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
谢谢我知道在没有if-else的情况下有很多方法可以做到这一点,我特别想问的是,是否只有使用列表理解才能做到这一点。我想我是在试图找出在列表理解中是否有访问索引的方法。[“first”如果I==0,否则“rest”对于I,枚举(x)中的值)]
将允许您访问索引您不能(明智地)修改列表理解中的变量,因此这是不可能的求和
对于一个产品来说是一个非常糟糕的名字…@Eric lol,是的,我意识到我把它改成了产品谢谢!是的,我不想那样做,它完全不可读。我只是想知道这是否可能。我因为好奇被投票否决了,耶!!!