Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么我';“我得到了这个错误”;类型错误:';列表';对象不能解释为整数;_Python_Itertools - Fatal编程技术网

Python 为什么我';“我得到了这个错误”;类型错误:';列表';对象不能解释为整数;

Python 为什么我';“我得到了这个错误”;类型错误:';列表';对象不能解释为整数;,python,itertools,Python,Itertools,我需要打印[‘香草’、‘巧克力酱’]、[‘巧克力’、‘巧克力酱’],但我得到一个错误: 回溯(最近一次呼叫最后一次): 文件“”,第15行,在文件“”中,第10行,在scoops中 TypeError:“列表”对象不能解释为整数 代码片段如下所示: from itertools import combinations class IceCreamMachine: def __init__(self, ingredients, toppings): self

我需要打印[‘香草’、‘巧克力酱’]、[‘巧克力’、‘巧克力酱’],但我得到一个错误:

回溯(最近一次呼叫最后一次): 文件“”,第15行,在文件“”中,第10行,在scoops中 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']]

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]))