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