到目前为止我所做的几乎没有什么
def dress_me(shirt, tie, suit): # if type(shirt) != list or type(tie) != list or type(suit) != list: # return None combinations = dress_me(shirt, tie, suit) for combo in combinations: print(combo)
答案 0 :(得分:4)
def dress_me(shirt, tie, suit):
if type(shirt) != list or type(tie) != list or type(suit) != list:
return None
return list(itertools.product(shirt, tie, suit))
演示:
>>> dress_me([1,2,3],[4,5,6],[7,8,9])
[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 6, 7), (1, 6, 8), (1, 6, 9), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 6, 7), (2, 6, 8), (2, 6, 9), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 6, 7), (3, 6, 8), (3, 6, 9)]
答案 1 :(得分:1)
或者,为了完整性,在没有额外功能的发电机方式中:
import itertools
for combination in itertools.product(shirts, ties, suits):
whatever_you_want_to_do(combination)
答案 2 :(得分:0)
def dress_me(shirt, tie, suit):
all_combinations = []
for s in shirt:
for t in tie:
for su in suit:
all_combinations.append((s,t,su))
return all_combination
也许有更多的pythonic方式:)
答案 3 :(得分:0)
因为看起来你想要提出递归解决方案,所以这是它的一般形式:
def all_perms(thing):
if len(thing) <=1:
yield thing
else:
for perm in all_perms(thing[1:]):
for i in range(len(perm)+1):
yield perm[:i] + thing[0:1] + perm[i:]
这适用于大多数类型的迭代。演示:
In [5]: list(all_perms(('shirt','tie','suit')))
Out[5]:
[('shirt', 'tie', 'suit'),
('tie', 'shirt', 'suit'),
('tie', 'suit', 'shirt'),
('shirt', 'suit', 'tie'),
('suit', 'shirt', 'tie'),
('suit', 'tie', 'shirt')]
起初很难理解递归,但一般形式是:
if simplest_case:
return simplest_case
else:
#recurse
在这种情况下,return
被yield
替换,以便生成一个更符合内存的生成器。你仍然不应该期望这是性能最佳的解决方案,但是我将它包括在内是为了完整性,因为“使用ITERTOOLS”并不会教你很多,除了itertools很酷。