Python 为什么我';“我得到了这个错误”;类型错误:';列表';对象不能解释为整数;
我需要打印[‘香草’、‘巧克力酱’]、[‘巧克力’、‘巧克力酱’],但我得到一个错误: 回溯(最近一次呼叫最后一次): 文件“”,第15行,在文件“”中,第10行,在scoops中 TypeError:“列表”对象不能解释为整数 代码片段如下所示:Python 为什么我';“我得到了这个错误”;类型错误:';列表';对象不能解释为整数;,python,itertools,Python,Itertools,我需要打印[‘香草’、‘巧克力酱’]、[‘巧克力’、‘巧克力酱’],但我得到一个错误: 回溯(最近一次呼叫最后一次): 文件“”,第15行,在文件“”中,第10行,在scoops中 TypeError:“列表”对象不能解释为整数 代码片段如下所示: from itertools import combinations class IceCreamMachine: def __init__(self, ingredients, toppings): self
from itertools import combinations
class IceCreamMachine:
def __init__(self, ingredients, toppings):
self.ingredients = ingredients
self.toppings = toppings
def scoops(self):
return list(combinations(self.ingredients,self.toppings))
if __name__ == "__main__":
machine = IceCreamMachine(["vanilla", "chocolate"], ["chocolate sauce"])
print(machine.scoops()) #should print[['vanilla', 'chocolate sauce'], ['chocolate', 'chocolate sauce']]
itertools.combines()
方法将第二个参数作为整数。
它生成在第一个参数中传递的iterable项的所有可能组合。
阅读更多
对于您的问题,您可以将scoop函数定义为
from itertools import product
def scoop(self):
return list(product(self.ingredients,self.toppings)))
组合(list,r)
采用两个参数,其中list是类似于[1,2,3]的Python列表,r表示由此生成的每个组合的长度
Ex组合([1,2,3],2)
将生成
[[1,2],[2,3],[1,3]]
您将第二个参数作为列表提供,这是错误的,因为它应该是一个整数看起来您正在寻找
itertools.product
from itertools import product
class IceCreamMachine:
def __init__(self, ingredients, toppings):
self.ingredients = ingredients
self.toppings = toppings
def scoops(self):
return list(product(self.ingredients, self.toppings))
if __name__ == "__main__":
machine = IceCreamMachine(["vanilla", "chocolate"], ["chocolate sauce"])
print(machine.scoops()) #should print[['vanilla', 'chocolate sauce'],
看看:组合(iterable:iterable,r:int)
您传递的第二个参数(self.toppings
)不匹配,导致TypeError:“list”对象不能解释为整数
但是,您可能需要使用itertools.product
:
import itertools
def scoops(self):
return list(itertools.product(self.ingredients, self.toppings))
组合函数定义为
combinations(iterable, r)
其中iterable在您的例子中是list,r是序列的长度,所以r应该是整数
你应该试试
return list(combinations([self.ingredients, self.toppings]))