Python - 生成句子中所有可能的單詞排列
當需要生成句子中某個單詞的所有可能排列時,需要定義一個函式。此函式遍歷該字串,根據條件顯示輸出。
示例
以下是相關演示
from itertools import permutations
def calculate_permutations(my_string):
my_list = list(my_string.split())
permutes = permutations(my_list)
for i in permutes:
permute_list = list(i)
for j in permute_list:
print j
print()
my_string = "hi there"
print("The string is :")
print(my_string)
print("All possible permutation are :")
calculate_permutations(my_string)輸出
The string is : hi there All possible permutation are : hi there there hi
說明
將所需的軟體包匯入環境。
定義一個名為“calculate_permutations”的方法,該方法將一個字串作為引數。
它基於空格進行分割。
這些單詞被轉換為列表並存儲在變數中。
對它進行迭代,並顯示在控制檯中。
在該方法外部,定義一個字串並顯示在控制檯中。
透過傳遞所需引數來呼叫該方法。
輸出顯示在控制檯中。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP