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

标签 python list

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

相关文章:

python - BigQuery python 插入记录 (\w client.insert_rows)

python - 如何检查字符串是否是字符串列表中项目的子字符串

java - 何时在 Java 中使用 Map 而不是 List?

python - SQLAlchemy 发送到数据库的调试(显示)SQL 命令

python - Pandas 十进制数到日期的转换

Python:可以支持多处理的 hyperopt 的替代方案?

删除嵌套在数据框列表中的列标题内的句点和空格

python - 将元素追加到列表中

c# - 如何找到列表之间的差异?

python - HTTP 000 连接失败