是否可以使用 list comprehension 模拟 sum() 之类的东西? ?
例如 - 我需要计算列表中所有元素的乘积:
list = [1, 2, 3]
product = [magic_here for i in list]
#product is expected to be 6
执行相同操作的代码:
def product_of(input):
result = 1
for i in input:
result *= i
return result
最佳答案
没有;列表推导式生成一个与其输入一样长的列表。您将需要 Python 的其他功能工具之一(在这种情况下特别是 reduce()
)到 fold将序列转换为单个值。
关于python - 如何使用列表推导模拟 sum()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16632124/