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 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下