通过带条件的生成器表达式分配两个变量?



下面的代码有一个字典,其中包含各种奶酪及其数量。然后,根据预先确定的销售项目列表,代码打印正在销售的奶酪总数与全价。

我正在使用生成器表达式来计算总数,但我想知道是否有办法压缩我的代码以同时分配具有某种 if-else 条件的sale_countfull_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))

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

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))

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

另一种方法是以下方法,但我同意@donkopotamus,如果您没有性能问题,wo 表达式是可以的。

sale_count, full_price_count  = map(sum, zip(*((v * (c in on_sale), v * (c not in on_sale)) for c, v in cheeses.items())))

它的可读性不是很强,但它在一行中可以满足您的需求:

[sale_count, full_price_count] = map(sum, zip(*[(qty, 0) if cheese in on_sale else (0, qty) for cheese, qty in cheeses.items()]))

最新更新