为什么我得到这个错误“TypeError:“list”对象不能解释为整数”

2024-10-02 04:29:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: 文件selfdef错误machineprintsaucetoppings
3条回答

combinations(list,r)接受两个参数,其中list是类似于[1,2,3]的Python列表,r表示由此生成的每个组合的长度

Excombinations([1,2,3],2)将生成

[[1,2],[2,3],[1,3]]

您将第二个参数作为列表提供,这是错误的,因为它应该是一个整数

itertools.combinations()方法将第二个参数作为整数。 它生成在第一个参数中传递的iterable项的所有可能组合。 阅读更多here

对于您的问题,您可以将scoop函数定义为

from itertools import product 
def scoop(self):
    return list(product(self.ingredients,self.toppings)))

看起来你在找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'],

相关问题 更多 >

    热门问题