-1

我需要帮助在 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')
4

3 回答 3

6

itertools救援。

import itertools

def dress_me(*choices):
  return itertools.product(*choices)
于 2013-08-08T07:12:45.757 回答
1
def dress_me(l1, l2, l3):
    return [(i, j, k) for i in l1 for j in l2 for k in l3]
于 2013-08-08T07:29:20.457 回答
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)
于 2013-08-08T07:27:08.837 回答