简体   繁体   English

返回两个列表的所有可能组合

[英]Return all possible combinations of two lists

I've tried to return all the possible combinations of two given lists using class the combination will have to consist of one element from each list.我尝试使用class返回两个给定列表的所有可能组合,该组合必须由每个列表中的一个元素组成。 I can do until the length of the second list is 1. But after increasing the length, I don't get the expected output.我可以做到直到第二个列表的长度为 1。但是增加长度后,我没有得到预期的 output。

as an example the code is例如,代码是

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

it returns the expected output which is [['vanilla', 'chocolate sauce'], ['chocolate', 'chocolate sauce']] but whenever I tend to increase the element of the second list it shows an incorrect answer.它返回预期的 output 这是[['vanilla', 'chocolate sauce'], ['chocolate', 'chocolate sauce']]但每当我倾向于增加第二个列表的元素时,它会显示一个不正确的答案。 Can anyone suggest me how to solve the problem?谁能建议我如何解决这个问题?

using itertools.product使用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())

output output

[('vanilla', 'chocolate sauce'), ('vanilla', 'banana sauce'), ('chocolate', 'chocolate sauce'), ('chocolate', 'banana sauce')]

I think this can be done by using two for-loop:我认为这可以通过使用两个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

use "for [variable] in [list]" can make the code looks simpler使用“for [variable] in [list]”可以使代码看起来更简单

def scoops(self):
    IceCreamList = []
    for i in self.ingredients:
        for j in self.toppings:
            IceCreamList.append([i,j])
    
    return IceCreamList

if you want to have the combination with more than one option, the code will be more complicated then this...如果你想有多个选项的组合,那么代码会更复杂......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM