使用 Python 内置函数实现给定字符串的排列
在本教程中,我们将使用 Python 的内置函数 **permutations** 来查找字符串的排列。**permutations** 方法位于 **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("-----------Permutations 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))输出
运行上述程序,您将得到以下结果。
-----------Permutations 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如果您对程序有任何疑问,请在评论区提出。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP