使用Python中的内置函数对给定的字符串进行排列
在本教程中,我们会发现使用的内置函数的字符串的排列Python的 所谓排列。方法排列 在itertools模块中。阅读文章以了解什么是排列。
查找字符串置换的过程
导入itertools 模块。
初始化字符串。
使用itertools.permutations方法查找字符串的排列。
在第三步中,该方法返回一个对象并将其转换为列表。
列表包含字符串的排列作为元组。
示例
让我们看一下程序。
## importing the module
import itertools
## initializing a string
string = "XYZ"
## itertools.permutations method
permutaion_list = list(itertools.permutations(string))
## printing the obj in list
print("-----------Permutaions Of String In Tuples----------------")
print(permutaion_list)
## converting the tuples to string using 'join' method
print("-------------Permutations In String Format-----------------")
for tup in permutaion_list:
print("".join(tup))输出结果
如果运行上述程序,将得到以下结果。
-----------Permutaions Of String In Tuples----------------
[('X', 'Y', 'Z'), ('X', 'Z', 'Y'), ('Y', 'X', 'Z'), ('Y', 'Z', 'X'), ('Z', 'X', 'Y'), ('Z', 'Y', 'X')]
-------------Permutations In String Format-----------------
XYZ
XZY
YXZ
YZX
ZXY
ZYX如果您对该程序有任何疑问,请在评论部分中提及它们。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下