[英]Python permutations including substrings
import itertools
def all_permutations_substrings(a_str):
return (
''.join(item)
for length in xrange(1, len(a_str)+1)
for item in itertools.permutations(a_str, length))
但请注意,这是真正的排列 - 例如, hello
将有任何子串排列,其中有两个l
s,因为l
将被视为“唯一”。 如果你想摆脱它,你可以通过set()
传递它:
all_permutations_no_dupes = set(all_permutations_substrings(a_str))
作为您链接状态的问题, itertools.permutations是用于生成列表排列的解决方案。 在python中,字符串可以被视为列表,因此itertools.permutations("text")
将正常工作。 对于子字符串,您可以将一个长度传递给itertools.permutations作为可选的第二个参数。
def permutate_all_substrings(text):
permutations = []
# All possible substring lengths
for length in range(1, len(text)+1):
# All permutations of a given length
for permutation in itertools.permutations(text, length):
# itertools.permutations returns a tuple, so join it back into a string
permutations.append("".join(permutation))
return permutations
或者,如果您更喜欢单行列表推导
list(itertools.chain.from_iterable([["".join(p) for p in itertools.permutations(text, l)] for l in range(1, len(text)+1)]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.