我知道如何在 python 中获取纯字符串的排列:
>>> from itertools import permutations
>>> perms = [''.join(p) for p in permutations('stack')]
>>> print perms
...
但是我如何获得 'stac'
、'stak'
、'sack'
、'stck' 的排列
、'stc'
、'st'
等等?我想要的输出是:
>>> permutations('pet')
['pet', 'pte', 'ept', 'etp', 'tpe', 'tep', 'pe', 'ep', 'p', 'e', 't', 'pt', 'tp', 'et', 'te']
我目前拥有的:
def permutate(values, size):
return map(lambda p: [values[i] for i in p], permutate_positions(len(values), size))
def permutate_positions(n, size):
if (n==1):
return [[n]]
unique = []
for p in map(lambda perm: perm[:size], [ p[:i-1] + [n-1] + p[i-1:] for p in permutate_positions(n-1, size) for i in range(1, n+1) ]):
if p not in unique:
unique.append(p)
return unique
def perm(word):
all = []
for k in range(1, len(word)+1):
all.append(permutate([' ']+list(word), k))
return all
这运行为:
>>> perm('pet')
[[['t'], ['e'], ['p']], [['t', 'e'], ['e', 't'], ['e', 'p'], ['t', 'p'], ['p', 't'], ['p', 'e'], ['p', 'p']], [['t', 'e', 'p'], ['e', 't', 'p'], ['e', 'p', 't'], ['e', 'p', 'p'], ['t', 'p', 'e'], ['p', 't', 'e'], ['p', 'e', 't'], ['p', 'e', 'p'], ['t', 'p', 'p'], ['p', 't', 'p'], ['p', 'p', 't'], ['p', 'p', 'e']]]
>>>
但是,它有一堆列表列表,并且具有 ['p', 'p', 't'] 之类的值!
我该怎么做?感谢任何帮助。
最佳答案
这是使用 itertools.permutations 实现的一种方式:
from itertools import permutations
s = 'pet'
print [''.join(p) for i in range(1, len(s)+1) for p in permutations(s, i)]
输出:
['p', 'e', 't', 'pe', 'pt', 'ep', 'et', 'tp', 'te', 'pet', 'pte', 'ept', 'etp', 'tpe', 'tep']
关于python - 如何获取字符串所有子串的每一个排列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23159200/