包含子字符串的Python置换

包含子字符串的Python置换,python,permutation,Python,Permutation,我遇到过这样的帖子: 但我需要更多的东西,即字符串的所有排列,以及所有子字符串的所有排列。我知道这是一个很大的数字,但有可能吗 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_st

我遇到过这样的帖子:

但我需要更多的东西,即字符串的所有排列,以及所有子字符串的所有排列。我知道这是一个很大的数字,但有可能吗

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


正如您链接状态的问题一样,是生成列表排列的解决方案。在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)]))

可能重复:您可以对它们进行迭代(例如,
以获得所有置换子字符串(…)
),或者如果您只需要一个列表,您可以将其传递到
list()
。@AnshumanDwibhashi,您可以这样做:
result=[''。对于集合中的元素(所有置换子字符串('hello'))加入(ele)
list(itertools.chain.from_iterable([["".join(p) for p in itertools.permutations(text, l)] for l in range(1, len(text)+1)]))