Python获得数字的所有排列

Sam*_*hin 6 python combinations

我试图显示数字列表的所有可能的排列,例如,如果我有334我想得到:

3 3 4
3 4 3
4 3 3
Run Code Online (Sandbox Code Playgroud)

我需要能够为任何长达12位左右的数字组执行此操作.

我确信使用像itertools.combinations这样的东西可能相当简单,但是我不能完全正确地使用语法.

TIA Sam

Sil*_*ost 27

>>> lst = [3, 3, 4]
>>> import itertools
>>> set(itertools.permutations(lst))
{(3, 4, 3), (3, 3, 4), (4, 3, 3)}
Run Code Online (Sandbox Code Playgroud)


gho*_*g74 5

没有迭代工具

def permute(LIST):
    length=len(LIST)
    if length <= 1:
        yield LIST
    else:
        for n in range(0,length):
             for end in permute( LIST[:n] + LIST[n+1:] ):
                 yield [ LIST[n] ] + end

for x in permute(["3","3","4"]):
    print x
Run Code Online (Sandbox Code Playgroud)

输出

$ ./python.py
['3', '3', '4']
['3', '4', '3']
['3', '3', '4']
['3', '4', '3']
['4', '3', '3']
['4', '3', '3']
Run Code Online (Sandbox Code Playgroud)