使用 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