[英]Combinations meeting certain numeric criteria
我需要生成組合並將輸出限制為滿足與組合相關的數字標准的某些組合。 以下是代碼:
import itertools
mylist = [('Beef', 1), ('Pepper', -1),('Onion', 6), ('Green', -1), ('Chicken', 4)]
lst = [item[0] for item in mylist]
combo = []
for i in range(1, 5):
for tpl in itertools.combinations(lst, i):
combo.append(tpl)
print(combo)
該代碼當前生成所有可能的組合。 我需要將結果限制為僅值是某個數值的那些組合。 例如,如果我的值是 9,那么應該使用“洋蔥”、“綠色”和“雞肉”或“洋蔥”、“雞肉”和“胡椒”來生成組合。 因為它們的數值加起來是 9 ( 6+4-1=9
)。 在這種情況下,牛肉被排除在組合生成之外。 我怎樣才能做到這一點?
不要將字符串分隔到不同的列表中,而是使用元組並在值上添加條件,並且只添加符合條件的字符串:
import itertools
goal = 9
mylist = [('Beef', 1), ('Pepper', -1),('Onion', 6), ('Green', -1), ('Chicken', 4)]
combo = []
for i in range(1, 5):
for tpl in itertools.combinations(mylist, i):
if sum(item[1] for item in tpl) == goal:
combo.append(tuple(item[0] for item in tpl))
print(combo)
對於上述goal = 9
的情況,這將給出:
[('Pepper', 'Onion', 'Chicken'), ('Onion', 'Green', 'Chicken')]
將元組列表分成兩個列表的更“pythonic”方法是轉置列表:
for tpl in itertools.combinations(mylist, i):
names, values = zip(*tpl)
if sum(values) == goal:
combo.append(names)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.