我有以下代码,它可以创建水果、蔬菜和饮料的组合,并保持在特定价格范围内:
fruits = [('apple', 1), ('banana', 2), ('orange', 3)]
veggies = [('tomato', 1), ('cucumber', 2), ('onion', 3)]
drinks = [('water', 1), ('juice', 2), ('soda', 3)]
for fruit1 in fruits:
for fruit2 in fruits:
for veggie1 in veggies:
for veggie2 in veggies:
for drink1 in drinks:
for drink2 in drinks:
if 12 <= fruit1[1]+fruit2[1]+veggie1[1]+veggie2[1]+drink1[1]+drink2[1] <= 14:
if fruit1 != fruit2:
if veggie1 != veggie2:
if drink1 != drink2:
combos.append((fruit1[0], fruit2[0], veggie1[0], veggie2[0], drink1[0], drink2[0], fruit1[1]+fruit2[1]+veggie1[1]+veggie2[1]+drink1[1]+drink2[1]))
它会检查以确保不会选择相同的水果/蔬菜/饮料两次,但我需要确保组合是独一无二的。
例如,如果最后得到了
('apple', 'banana', 'tomato', 'cucumber', 'water', 'soda', 10)
我不想要
('banana', 'apple', 'tomato', 'cucumber', 'water', 'soda', 10)
等等等。这比我想象的更麻烦,所以任何帮助都将不胜感激。
a <= b <= c
相当于a <= b and b <= c
。(连锁比较运算符) - falsetru