首页 > 解决方案 > 通过带有条件的生成器表达式分配两个变量?

问题描述

下面的代码有一个包含各种奶酪及其数量的字典。根据预先确定的销售项目清单,代码会打印出销售的奶酪总量与全价的对比。

我正在使用生成器表达式来计算总数,但我想知道是否有一种方法可以压缩我的代码以使用某种 if-else 条件同时分配sale_count和变量,因为生成器的代码实际上是full_price_count相同的。

cheeses = {'gouda': 3, 'cheddar': 7, 'american': 2, 'mozzarella': 5}
on_sale = ['american', 'blue cheese', 'cheddar', 'provolone', 'swiss']

# if the cheese is on sale, add its quantity to sale_count
# otherwise, add its quantity to full_price_count
sale_count = sum(qty for (cheese, qty) in cheeses.items() if cheese in on_sale)
full_price_count = sum(qty for (cheese, qty) in cheeses.items() if cheese not in on_sale)

print("Sale count: {}\nFull price count: {}".format(sale_count, full_price_count))

标签: pythonpython-3.xgeneratorgenerator-expression

解决方案


它可以在一个表达式中完成,如下所示:

functools.reduce(
    lambda x, y: (x[0] + y[0], x[1] + y[1]),
    ((qty, 0) if cheese in on_sale else (0, qty) for cheese, qty in cheeses.items()), 
    (0, 0))

但是,与其他潜在答案一样,这可能会真正回答为什么当两个完全清楚时,事情并不总是必须简化为一个表达式。


推荐阅读