我遇到了这篇帖子:如何在Python中生成列表的所有排列
但是我需要更多,即一个字符串的所有排列以及所有子字符串的排列。我知道它是很大的数字,但是可能吗?
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
的子字符串排列出现两次,因为这些 l
被视为“独特的”。如果你想要消除这种情况,可以通过一个 set()
处理它:
all_permutations_no_dupes = set(all_permutations_substrings(a_str))
for result in all_permutations_substrings(...)
),或者如果你只想要一个列表,可以将其传递给 list()
。 - Amberresult = [''.join(ele) for ele in set(all_permutations_substrings('hello'))]
- Akavallitertools.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)]))