通过生成器表达式分配两个变量w / conditional?

时间:2018-05-06 21:02:16

标签: python python-3.x generator generator-expression

以下代码包含一个包含各种奶酪及其数量的字典。根据预先确定的销售商品清单,代码然后打印出售的奶酪总价格与全价。

我正在使用生成器表达式计算总数,但我想知道是否有办法压缩我的代码以同时分配sale_countfull_price_count变量以及某种if - 条件,因为发电机的代码实际上是相同的。

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

3 个答案:

答案 0 :(得分:2)

可以在单个表达式中完成:

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

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

答案 1 :(得分:0)

它不是很易读,但它可以在一行中完成您想要的任务:

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

答案 2 :(得分:0)

另一种方法是做以下几点,但我同意@donkopotamus,如果你没有性能问题,那么表达式就可以了。

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())))
相关问题