我有使用Python的itertools庫的這個函數創建一個列表(實際上是一個迭代器):這種格式如何只選擇字符串/整數列表中的整數?
comb = [c for i in range(len(menu)+1) for c in combinations(menu, i)]
爲了給你一個想法menu
的列表[「食品名稱」,克糖]的:
menu = [ ["cheesecake", 13], ["pudding", 24], ["bread", 13], .........]
所以comb
本質上是包含了所有菜單子列表的可能組合的列表。我必須通過梳理創建所有可能的項目組合,其總糖含量將完全等於(不少,不會更多,正確)max_sugar = 120
。
所以我想我可以遍歷comb
中的每個可能的組合,並檢查一個if
陳述,如果這個組合中物品的糖的總和等於完全max_sugar
。如果是這種情況,我想輸出這個組合中菜單項的名稱。否則,我想通過其他組合繼續以這種方式:
for e in comb:
for l in e:
if sum(sugars of items in this combination) == max_sugar: # pseudo-code
print items in this combination #pseudo code
我想我遇到的問題是在l
來訪問每個項目只有糖值和檢查條件,如果它是TRUE
打印名。 我不擅長Python列表解析,但在過去的幾天裏我已經有了很多改進!
flag = 0
num_comb = 1
comb = [c for i in range(len(menu)+1) for c in combinations(menu, i)]
for e in comb:
if sum(l[1] for l in e) == targetSugar:
print "The combination number " + str(num_comb) + " is:\n"
print([l[0] for l in e])
print "\n\n\n"
num_comb += 1
flag = 1
if flag == 0:
print "there are no combinations of dishes for your sugar intake... Sorry! :D "
更清晰地使用拆包,即''爲名,糖在電子' – wim
這是一個很好的觀點,謝謝;編輯 – jonrsharpe
謝謝大家的幫忙!現在有很多意義! – user3245453