I need help coming up with a function in python that can take 3 arguements as lists and give me all combinations of there elements
本问题已经有最佳答案,请猛点这里访问。
到目前为止我所拥有的几乎什么都没有
1
2
3
4
5
6
7
8 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)
号
使用
1 2 3 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)) |
演示:
1 2 | >>> 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 2 3 4 | import itertools for combination in itertools.product(shirts, ties, suits): whatever_you_want_to_do(combination) |
由于看起来您试图提出一个递归的解决方案,下面是它的一般形式:
1 2 3 4 5 6 7 | 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:] |
这适用于大多数类型的iTerables。演示:
1 2 3 4 5 6 7 8 | 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')] |
递归一开始很难理解,但一般形式是:
1 2 3 4 | if simplest_case: return simplest_case else: #recurse |
在这种情况下,
1 2 3 4 5 6 7 | 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 |
也许还有一个更像Python的方法来做它:)