Python排列包括子串

5

1
可能是重复问题:https://dev59.com/p2jWa4cB1Zd3GeqPnBI8 - bdean20
2个回答

5
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() - Amber
@AnshumanDwibhashi,你可以这样做:result = [''.join(ele) for ele in set(all_permutations_substrings('hello'))] - Akavall

1
正如您链接的问题所述,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)]))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接