我需要打印['vanilla','chocolate sauce'],['chocolate','chocolate sauce'],但出现错误:
回溯(最近通话最近): 文件“”,第15行,在文件“”,第10行,在独家新闻 TypeError:“列表”对象无法解释为整数
代码段如下:
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']]
答案 0 :(得分:2)
好像您在寻找select *
from #Fruits
where
Fruit in ('Apple', 'Grapes') or
(Color = 'Green' and
not exists (select 1 from #Fruits where Fruit in ('Apple', 'Grapes'));
,
itertools.product
答案 1 :(得分:1)
itertools.combinations()
方法将第二个参数作为整数。
它生成在第一个参数中传递的可迭代项的所有可能组合。
了解更多here
对于您的问题,您可以将scoop函数定义为
from itertools import product
def scoop(self):
return list(product(self.ingredients,self.toppings)))
答案 2 :(得分:1)
combinations(list,r)
带有两个参数,其中 list 是Python列表,例如[1,2,3],而 r 表示由此生成的每个组合的长度>
Ex combinations([1,2,3],2)
将生成
[[1,2],[2,3],[1,3]]
您要提供第二个参数作为列表,这是错误的,因为它应该是整数
答案 3 :(得分:1)
看看method signature:combinations(iterable: Iterable, r: int)
。
您传递的第二个参数(self.toppings
)不匹配,结果为TypeError: 'list' object cannot be interpreted as an integer
但是,您可能想要使用itertools.product
:
import itertools
def scoops(self):
return list(itertools.product(self.ingredients, self.toppings))
答案 4 :(得分:1)
组合功能定义为
combinations(iterable, r)
其中iterable是您的情况下的列表,并且r是序列的长度,因此r应该是整数
您应该尝试
return list(combinations([self.ingredients, self.toppings]))