Python字符串的所有可能组合

编程入门 行业动态 更新时间:2024-10-09 10:20:13
本文介绍了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字符串的所有可能组合

本文发布于:2023-11-30 07:28:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649169.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   字符串   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!