本文介绍了Python字符串的所有可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在使用python,正在尝试编写一个给定字符串的方法,它将找到该字符串的每个组合并将其附加到列表中.我将给出字符串并显示所需的结果.

Hi so I'm working with python and I'm trying to write a method where given a string, it would find every combination of that string and append it to a list. I'll give the string and show the outcome that I want.

字符串: x ='上帝'

结果:

lst = ['g', 'o', 'd', 'go', 'gd', 'og', 'od', 'dg', 'do', 'god', 'gdo', 'ogd', 'odg', 'dgo', 'dog']

字母只能使用出现在给定字符串上的次数,因此,如果我们的字符串是'god''gg''goo'等不能附加.如果可以使用递归来做到这一点,那就太好了!

A letter can only be used by the number of times it appears on the string given, so if our string is 'god', 'gg' or 'goo' etc. cannot be appended. If this could be done using recursion that would be great!

推荐答案

使用排列:

from itertools import permutations

x = 'god'


perms = []

for i in range(1, len(x)+1):
    for c in permutations(x, i):
        perms.append("".join(c))

print(perms)
# ['g', 'o', 'd', 'go', 'gd', 'og', 'od', 'dg', 'do', 'god', 'gdo', 'ogd', 'odg', 'dgo', 'dog']

这篇关于Python字符串的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 16:43