2017-08-30 144 views
-1

我一直在试图创建一个脚本,其中列表的每个可能的组合都将被打印[其中(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)

+6

但是您显示的输出_does_都包含'(1,2)'和'(2,1)'。 – khelwood

+0

[如何在Python中生成列表的所有排列]可能的重复(https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python) –

回答

1

工作对我来说:

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

产生

(1, 2) 
(2, 1) 
+0

谢谢。它的确如此。但是,它并没有将(1,1)和(2,2)等所有元素结合起来。对于令人困惑的标题感到抱歉。 –

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开始使用。

+0

谢谢你,先生。这正是我想要的。 –

1

可能有一些内置(或更可能是numpy)的包可以为你做到这一点,但它是一个很好的练习自己做。

有一个问题 - 你对长度2置换感兴趣吗?或者你想写一个任意长排列的函数吗?

此外,见:How to generate all permutations of a list in Python

+0

这并没有真正回答这个问题。 –

+0

@cᴏʟᴅsᴘᴇᴇᴅ然而,它显示,他是值得*评论*所需的50名代表。这就是我反正提高的原因。但Coldspeed是对的Mike。这将作为评论更合适,而不是回答。 –

+0

不能确定是否适合编码初学者的例子,选择提供一些高层次的想法 –

0

请与更换组合,然后置换的结果,只保留独特的效果。

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)] 
相关问题