我有一串字母,我想拆分成所有可能的组合(字母的顺序必须保持固定),这样:
s = 'monkey'
变成:
combinations = [['m', 'onkey'], ['mo', 'nkey'], ['m', 'o', 'nkey'] ... etc]
有什么想法吗?
最佳答案
def splitter(str):
for i in range(1, len(str)):
start = str[0:i]
end = str[i:]
yield (start, end)
for split in splitter(end):
result = [start]
result.extend(split)
yield result
combinations = list(splitter(str))
请注意,我默认使用生成器,以免您因长字符串而耗尽内存。
关于python - 在Python中查找拆分字符串的所有列表排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4904430/