我需要帮助在Python中提供一个函数,它接受3个参数作为列表,并且可以返回所有组合。
例如,如果我跑了:
shirts = ['white', 'blue']
ties = ['purple', 'yellow']
suits = ['grey', 'blue']
combinations = dress_me(shirts, ties, suits)
for combo in combinations:
print combo
它会打印出类似的内容:
('white', 'purple', 'grey')
('white', 'purple', 'blue')
('white', 'yellow', 'grey')
('white', 'yellow', 'blue')
('blue', 'purple', 'grey')
('blue', 'purple', 'blue')
('blue', 'yellow', 'grey')
('blue', 'yellow', 'blue')
答案 0 :(得分:6)
itertools
救援。
import itertools
def dress_me(*choices):
return itertools.product(*choices)
答案 1 :(得分:1)
def dress_me(l1, l2, l3):
return [(i, j, k) for i in l1 for j in l2 for k in l3]
答案 2 :(得分:0)
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)