[英]All combinations of list wIthout itertools
我正在尝试创建一个递归函数,以查找python列表的所有组合。
我想在函数中输入['a','b','c'],并且在函数运行时,我希望跟踪显示如下:
['a','b','c']
['['a','a'],['b','a'],['c','a']]
['['a','a','b'],['b','a','b'],['c','a','b']]
['['a','a','b','c'],['b','a','b','c'],['c','a','b','c']]
我的递归函数如下所示:
def combo(lst,new_lst = []):
for item in lst:
new_lst.append([lst[0],item])
print([lst[0],item])
return combo(new_lst,lst[1:])
正确的答案是您应该使用itertools.combinations
。 但是,如果由于某种原因您不想这样做,并且想编写一个递归函数,则可以使用以下代码。 它是对生成组合的erlang方法的一种改编,因此乍一看似乎有点奇怪:
def combinations(N, iterable):
if not N:
return [[]]
if not iterable:
return []
head = [iterable[0]]
tail = iterable[1:]
new_comb = [ head + list_ for list_ in combinations(N - 1, tail) ]
return new_comb + combinations(N, tail)
这是思考大小为N
的组合的一种非常优雅的方式:您将可迭代( 头 )的第一个元素与其他可迭代( 尾 )的较小的( N-1
)组合在一起。 然后,向其添加相同大小的尾巴组合( N
)。 这就是您获得所有可能组合的方式。
如果需要所有长度的所有组合,则可以执行以下操作:
for n in range(1, len(iterable) + 1):
print(combinations(n, iterable))
似乎需要列表的所有乘积,可以在以下函数中使用itertools.product
返回生成器列表:
>>> from itertools import product
>>> def pro(li):
... return [product(l,repeat=i) for i in range(2,len(l)+1)]
...
>>> for i in pro(l):
... print list(i)
...
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'b', 'a'), ('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'c', 'a'), ('a', 'c', 'b'), ('a', 'c', 'c'), ('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'a', 'c'), ('b', 'b', 'a'), ('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'c', 'a'), ('b', 'c', 'b'), ('b', 'c', 'c'), ('c', 'a', 'a'), ('c', 'a', 'b'), ('c', 'a', 'c'), ('c', 'b', 'a'), ('c', 'b', 'b'), ('c', 'b', 'c'), ('c', 'c', 'a'), ('c', 'c', 'b'), ('c', 'c', 'c')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.