是否可以使用 sum() 来模拟类似的东西列表理解 http://en.wikipedia.org/wiki/List_comprehension#Python ?
例如 - 我需要计算列表中所有元素的乘积:
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 http://en.wikipedia.org/wiki/Fold_%28higher-order_function%29将序列转换为单个值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)