我嘗試使用class回傳兩個給定串列的所有可能組合,該組合必須由每個串列中的一個元素組成。我可以做,直到第二個串列的長度為 1。但增加長度后,我沒有得到預期的輸出。
例如,代碼是
class IceCreamMachine:
def __init__(self, ingredients, toppings):
self.ingredients = ingredients
self.toppings = toppings
def scoops(self):
IceCreamList = []
for i in range(len(self.ingredients)):
IceCreamList.append([self.ingredients[i], self.toppings[i%len(self.toppings)]])
return IceCreamList
machine = IceCreamMachine(["vanilla", "chocolate"], ["chocolate sauce"])
print(machine.scoops())
它回傳預期的輸出[['vanilla', 'chocolate sauce'], ['chocolate', 'chocolate sauce']]但是每當我傾向于增加第二個串列的元素時,它就會顯示一個不正確的答案。誰能建議我如何解決問題?
uj5u.com熱心網友回復:
使用 itertools.product
import itertools
class IceCreamMachine:
def __init__(self, ingredients, toppings):
self.ingredients = ingredients
self.toppings = toppings
def scoops(self):
return list(itertools.product(self.ingredients,self.toppings))
machine = IceCreamMachine(["vanilla", "chocolate"], ["chocolate sauce","banana sauce"])
print(machine.scoops())
輸出
[('vanilla', 'chocolate sauce'), ('vanilla', 'banana sauce'), ('chocolate', 'chocolate sauce'), ('chocolate', 'banana sauce')]
uj5u.com熱心網友回復:
我認為這可以通過使用兩個 for 回圈來完成:
def scoops(self):
IceCreamList = []
for i in range(len(self.ingredients)):
for j in range(len(self.toppings)):
IceCreamList.append([self.ingredients[i], self.toppings[j]])
return IceCreamList
使用“for [variable] in [list]”可以讓代碼看起來更簡單
def scoops(self):
IceCreamList = []
for i in self.ingredients:
for j in self.toppings:
IceCreamList.append([i,j])
return IceCreamList
如果你想有多個選項的組合,代碼會比這個更復雜......
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/375667.html
下一篇:使用FLTK的C 多重繼承問題
