1

I am new to python.

I have got a string separted by comma. Like 'a,b,c,d'

I need to separate get the elements separated and then need to find all the possible arrangements for the comma separated elements.

Thanks

4

3 回答 3

7

您可以使用 itertools 模块的排列

>>> a = 'aaa,bbb,ccc'
>>> b = a.split(',')
>>> import itertools
>>> list(itertools.permutations(b))
>>> [('aaa', 'bbb', 'ccc'), ('aaa', 'ccc', 'bbb'), ('bbb', 'aaa', 'ccc'), ('bbb', 'c
cc', 'aaa'), ('ccc', 'aaa', 'bbb'), ('ccc', 'bbb', 'aaa')]
于 2013-07-24T11:21:30.743 回答
3

你在找itertools.permutations()吗?

>>> import itertools
>>> for elem in itertools.permutations(testStr.split(',')):
        print ",".join(elem)


a,b,c,d
a,b,d,c
a,c,b,d
a,c,d,b
a,d,b,c
a,d,c,b
b,a,c,d
...
于 2013-07-24T11:23:09.300 回答
0

itertools是最好的

这是传统的递归技术

def permu(s, e=''):
    if len(s) == 0: print ",".join([ i for i in e])
    else:
        for i in range(len(s)):
            permu(s[0:i] + s[i+1:], e+s[i])

str="a,b,c,d"
permu("".join(str.split(',')))
于 2013-07-24T11:38:03.767 回答