是否可以使用列表理解来模拟sum()之类的东西?
例如 - 我需要计算列表中所有元素的乘积:
list = [1, 2, 3]
product = [magic_here for i in list]
#product is expected to be 6
Run Code Online (Sandbox Code Playgroud)
执行相同的代码:
def product_of(input):
result = 1
for i in input:
result *= i
return result
Run Code Online (Sandbox Code Playgroud)
jam*_*lak 40
>>> from operator import mul
>>> nums = [1, 2, 3]
>>> reduce(mul, nums)
6
Run Code Online (Sandbox Code Playgroud)
在Python 3上,您需要添加此导入: from functools import reduce
在Python 2.5/ 2.6您可以vars()['_[1]']用来引用当前正在构建的列表理解.这很糟糕,永远不应该使用,但它与你在问题中提到的最接近(使用list comp来模拟产品).
>>> nums = [1, 2, 3]
>>> [n * (vars()['_[1]'] or [1])[-1] for n in nums][-1]
6
Run Code Online (Sandbox Code Playgroud)
Pat*_*ick 12
列表理解总是创建另一个列表,因此它在组合它们时没有用处(例如,给出一个数字).此外,除非你是超级偷偷摸摸,否则没有办法在列表理解中进行任务.
我唯一一次看到使用列表推导对sum方法有用的唯一一次是你只想在列表中包含特定值,或者你没有数字列表:
list = [1,2,3,4,5]
product = [i for i in list if i % 2 ==0] # only sum even numbers in the list
print sum(product)
Run Code Online (Sandbox Code Playgroud)
或另一个例子":
# list of the cost of fruits in pence
list = [("apple", 55), ("orange", 60), ("pineapple", 140), ("lemon", 80)]
product = [price for fruit, price in list]
print sum(product)
Run Code Online (Sandbox Code Playgroud)
超级偷偷摸摸的方式在列表理解中进行任务
dict = {"val":0}
list = [1, 2, 3]
product = [dict.update({"val" : dict["val"]*i}) for i in list]
print dict["val"] # it'll give you 6!
Run Code Online (Sandbox Code Playgroud)
......但那太可怕了:)
像这样:
>>> a = [1,2,3]
>>> reduce(lambda x, y: x*y, a)
6
Run Code Online (Sandbox Code Playgroud)
从开始Python 3.8,并引入赋值表达式(PEP 572)(:=运算符),我们可以在列表推导中使用和增加变量,从而将列表简化为其元素的总和:
total = 0
[total := total + x for x in [1, 2, 3, 4, 5]]
# 15
Run Code Online (Sandbox Code Playgroud)
这个:
total为0total由当前循环的项目(total := total + x)递增我用一些使用reducePython运算符的代码来补充Ignacio Vazquez-Abrams的答案。
list_of_numbers = [1, 5, 10, 100]
reduce(lambda x, y: x + y, list_of_numbers)
Run Code Online (Sandbox Code Playgroud)
也可以写成
list_of_numbers = [1, 5, 10, 100]
def sum(x, y):
return x + y
reduce(sum, list_of_numbers)
Run Code Online (Sandbox Code Playgroud)
奖励:Python在内置函数中提供了此sum功能。这是最易读的imo表达式。
list_of_numbers = [1, 5, 10, 100]
sum(list_of_numbers)
Run Code Online (Sandbox Code Playgroud)