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("字符串是:")
print(my_string)
print("所有可能的排列是:")
calculate_permutations(my_string)输出结果字符串是: hi there 所有可能的排列是: hi there there hi
解释
所需的包被导入到环境中。
定义了一个名为“calculate_permutations”的方法,它接受一个字符串作为参数。
它是根据空格分割的。
这些词被转换为一个列表并存储在一个变量中。
它被迭代,并显示在控制台上。
在该方法之外,定义了一个字符串并显示在控制台上。
通过传递所需的参数来调用该方法。
输出显示在控制台上。
热门推荐
1 泰迪狗狗如何训练
3 狗狗训练图
5 狗狗训练方法
6 训练狗狗不咬人
8 敏捷训练狗狗
10 训练狗狗吃饭
11 泰迪狗狗训练
12 狗狗从多大开始训练
13 狗狗训练学校费用
14 怎么去训练狗狗
15 狗狗训练狗狗
16 狗狗训练教程
17 训练狗狗装死
18 泰迪狗狗的训练方法