gpt4 book ai didi

python - 如何使用列表推导模拟 sum()?

转载 作者:IT老高 更新时间:2023-10-28 22:12:54 25 4
gpt4 key购买 nike

是否可以使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com