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”的方法,它接受一个字符串作为参数。
它是根据空格分割的。
这些词被转换为一个列表并存储在一个变量中。
它被迭代,并显示在控制台上。
在该方法之外,定义了一个字符串并显示在控制台上。
通过传递所需的参数来调用该方法。
输出显示在控制台上。
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语