列表理解总是会创建另一个列表,所以在组合它们时没有用(例如给出一个单一的数字)。另外,除非你超级偷偷摸摸,否则无法在列表理解中进行任务。
我曾经看到使用列表理解为有用的方法和唯一的一次是,如果你只是想在列表中包含特定的值,或者你没有号码的清单:
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)
或另一个例子“:
# 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)
超级偷偷摸摸的方式,使在一个列表理解的分配
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!
...但是,这太可怕了:)
可能重复[像sum()那样的Python函数,但用于乘法?产品()?](http://stackoverflow.com/questions/595374/whats-the-python-function-like-sum-but-for-multiplication-product) –