如何使用列表推导模拟sum()? [英] How to emulate sum() using a list comprehension?

查看:105
本文介绍了如何使用列表推导模拟sum()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用列表理解来模拟类似sum()的东西?

Is it possible to emulate something like sum() using list comprehension ?

例如-我需要计算列表中所有元素的乘积:

For example - I need to calculate the product of all elements in a list :

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())来将序列折叠为单个值.

No; a list comprehension produces a list that is just as long as its input. You will need one of Python's other functional tools (specifically reduce() in this case) to fold the sequence into a single value.

这篇关于如何使用列表推导模拟sum()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆