繁体   English   中英

生成列表中元素的所有可能组合

[英]Generate all possible combinations of elements in a list

我一直在尝试创建一个脚本,在该脚本中将打印列表的每个可能组合[其中(1,2)和(2,1)将被计为不同的条目] 例如:

c = [1,2]
# do something magical
print(c with magical stuff) 
>>>[(1), (2), (1, 1), (1, 2), (2, 1), (2, 2)]

我已经尝试过itertools.permutations。 输出显示为>>>()(1,)(2,)(1、2)(2,1)。 但是,它不包括(1,1)和(2,2)

任何帮助将不胜感激。 我是编码的新手(虽然我很流利于打印“ Hello World!”:3)

尝试itertools.product

def foo(l):
    yield from itertools.product(l)
    yield from itertools.product(l, l)

for x in foo([1, 2]):
     print(x)

(1,)
(2,)
(1, 1)
(1, 2)
(2, 1)
(2, 2)

需要注意的是, yield from的语法可从python3.3开始。

为我工作:

c = [1,2]
for i in itertools.permutations(c):
     print i

产量

(1, 2)
(2, 1)

可能有一些内置的(或更可能是numpy)软件包可以为您完成此操作,但这是您自己进行的极好的练习。

一个问题-您是否只对length-2排列感兴趣,还是要编写一个用于任意长排列的函数?

另请参见: 如何在Python中生成列表的所有排列

通过替换组合,然后置换结果,仅保留唯一的结果。

import itertools as it 


combs = it.chain.from_iterable(it.combinations_with_replacement(c, i) for i in range(1,3))
perms = it.chain.from_iterable([set(it.permutations(i)) for i in combs])
list(perms)
# [(1,), (2,), (1, 1), (1, 2), (2, 1), (2, 2)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM