迭代要獲得所有的連擊,我需要將列表中的一個元素與每個其他列表中的一個元素相加。
聽起來像是你想itertools.product
。爲了簡化的例子,讓我們只需要三年的七個項目中(但它的瑣碎傳遞更多或更少,參數爲product
):
import itertools
b = [45] # I assume this represents the "bar" and that it's not optional
ts = [0, 5, 10, 15]
fs = [0, 10]
combos = itertools.product(b, ts, fs)
for combo in combos: print(list(combo))
打印以下內容:
[45, 0, 0]
[45, 0, 10]
[45, 5, 0]
[45, 5, 10]
[45, 10, 0]
[45, 10, 10]
[45, 15, 0]
[45, 15, 10]
...這聽起來像你想要的時候你所說的「所有組合」。
要獲得每個的總和,它都可以在一個行來完成:
totals = [sum(combo) for combo in itertools.product(b, ts, fs)]
下面是參數化功能的一個可能的靈活的方式:
import itertools
def PossibleWeights(*weights):
return list(itertools.product(*[[weightset] if isinstance(weightset, (int, float)) else [sum(weightset[:i]) for i in range(len(weightset)+1)] for weightset in weights]))
你打電話時,說, PossibleWeights(45, [10]*2, [5]*3)
該調用本身使其明確(可讀),即有一個強制性的45磅重,兩個可能的10磅重和三個可能的5磅重。對於您傳遞了多少個這樣的參數以及它們的值是什麼,您擁有完全的靈活性。
然後,您可以使用dict
每個總重量來實現它(順便說一句刪除重複的總數,有超過一個的組合加起來相同的總)組合關聯:
d = {}
for combo in PossibleWeights(45, [10]*2, [5]*3):
d[sum(combo)] = combo
.. 。而再漂亮,打印結果:
for total, combo in sorted(d.items()):
print('sum(%r) = %r' % (combo, total))
輸出:
sum((45, 0, 0)) = 45
sum((45, 0, 5)) = 50
sum((45, 10, 0)) = 55
sum((45, 10, 5)) = 60
sum((45, 20, 0)) = 65
sum((45, 20, 5)) = 70
sum((45, 20, 10)) = 75
sum((45, 20, 15)) = 80
順便說一句:如果你想要使用最少數量的印版達到每個印版總數,請確保在打電話給PossibleWeights
時,在較輕的印版之前通過較重的印版,如上例所示。
平衡杆的兩側作爲練習留給讀者;-)
談論你的代碼時,您可以使用像「架子」和「板」,但他們無處出現在你的代碼。因此很難理解你正在談論的任何事情。 – Denziloe