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

如果您對程式有任何疑問,請在評論區提出。

更新於:2021年4月16日

3K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.