关于python:获取3个列表参数并返回所有组合的函数

Function that takes 3 list arguments and returns all the combinations

本问题已经有最佳答案,请猛点这里访问。

我需要帮助在python中开发一个函数,它接受3个参数,这些参数是列表,可以返回所有组合。

例如,如果我运行:

1
2
3
4
5
6
shirts = ['white', 'blue']
ties = ['purple', 'yellow']
suits = ['grey', 'blue']
combinations = dress_me(shirts, ties, suits)
for combo in combinations:
    print combo

它将打印如下内容:

1
2
3
4
5
6
7
8
('white', 'purple', 'grey')
('white', 'purple', 'blue')
('white', 'yellow', 'grey')
('white', 'yellow', 'blue')
('blue', 'purple', 'grey')
('blue', 'purple', 'blue')
('blue', 'yellow', 'grey')
('blue', 'yellow', 'blue')


itertools去营救。

1
2
3
4
import itertools

def dress_me(*choices):
  return itertools.product(*choices)

1
2
def dress_me(l1, l2, l3):
    return [(i, j, k) for i in l1 for j in l2 for k in l3]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def dress_me(l1, l2, l3):
    res = []
    for i in l1:
        for j in l2:
            for k in l3:
                res.append((i, j, k))
    return res

shirts = ['white', 'blue']
ties = ['purple', 'yellow']
suits = ['grey', 'blue']

if __name__ == '__main__':  
    combinations = dress_me(shirts, ties, suits)
    for combo in combinations:
        print(combo)