我遇到了一个简单的python问题,要解决:拥有3类商品及其对应值的列表,在3个列表中打印出总价值低于X的所有组合。(代码示例可能更清楚地说明)。
我设法使用zip()和itertools.product()创建了组合,但要输出正确的组合,我觉得必须有一种更好的,更Python化的方式来表达输出通过压缩产品的内部元组来获得价格的总和,而无需创建2个明确的生成器/列表(我相信这种情况下用例并不重要)。来自Java的背景,有时我仍然遇到一些问题,有时无法陷入类似于Java的语法中,这是我绝对希望在Python中避免的问题。
这是我的代码:
import itertools
# Print out all possible meal combinations under $30
main_courses = ['beef stew', 'fried fish']
price_main_courses = [28, 23]
desserts = ['ice-cream', 'cake']
price_desserts = [2, 4]
drinks = ['cola', 'wine']
price_drinks = [3, 10]
products = itertools.product(
zip(main_courses, price_main_courses),
zip(desserts, price_desserts),
zip(drinks, price_drinks)
)
for combo in products:
names = (x[0] for x in combo)
price = sum((x[1] for x in combo))
if price <= 30:
print(*names, price)
基于this,for循环可写为:
for combo in products:
names, prices = zip(*combo)
price = sum(prices)
if price <= 30:
print(*names, price)
嗯,我唯一要做的就是使用列表推导而不是for循环,例如:
import itertools
# Print out all possible meal combinations under $30
main_courses = ['beef stew', 'fried fish']
price_main_courses = [28, 23]
desserts = ['ice-cream', 'cake']
price_desserts = [2, 4]
drinks = ['cola', 'wine']
price_drinks = [3, 10]
products = itertools.product(
zip(main_courses, price_main_courses),
zip(desserts, price_desserts),
zip(drinks, price_drinks)
)
combos = [
combo for combo in products if sum(price for name, price in combo) <= 30
]
for combo in combos:
print(' + '.join(name for name, price in combo), '=', sum(price for name, price in combo))
>>> "fried fish + ice-cream + cola = 28"
>>> "fried fish + cake + cola = 30"