python - 通过带有条件的生成器表达式分配两个变量?
问题描述
下面的代码有一个包含各种奶酪及其数量的字典。根据预先确定的销售项目清单,代码会打印出销售的奶酪总量与全价的对比。
我正在使用生成器表达式来计算总数,但我想知道是否有一种方法可以压缩我的代码以使用某种 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))
解决方案
它可以在一个表达式中完成,如下所示:
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))
但是,与其他潜在答案一样,这可能会真正回答为什么当两个完全清楚时,事情并不总是必须简化为一个表达式。
推荐阅读
- azure-functions - 共享环境中的功能/应用程序服务内存不受探测文档的影响 - 跨租户黑客
- c# - datatables asp.net core razor pages IActionResult new JsonResult
- bash - 在 dockerfile 中加载 2 个进程?
- angular - 角度选择元素的 ngModel 不正确
- c# - 事件流和事件溯源
- time-complexity - theta(1) 在 n 次的总和是 theta(log n base 2)
- vba - VBA
- MyString 语句在代码中的作用如何? - j - J中的每个前置副词
- javascript - 使用Angular ngModel在输入类型日期中格式化日期时间
- visual-studio - 如何覆盖 docker-compose.vs.debug.g.yml 中的 Visual Studio 容器工具调试器卷?