包括子字符串的Python排列



我看到了这篇文章:如何在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))

作为您链接状态的问题,itertools.permutations是生成列表排列的解决方案。在python中,字符串可以被视为列表,所以itertools.permutations("text")可以正常工作。对于子字符串,可以将长度作为可选的第二个参数传递给itertools.permutation。

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)]))

最新更新