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
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
您可以使用 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')]
>>> 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
...
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(',')))