Python - 生成句子中单词的所有可能排列
pythonserver side programmingprogramming更新于 2025/11/8 19:24:17
当需要生成句子中单词的所有可能排列时,会定义一个函数。此函数对字符串进行迭代,并根据条件显示输出。
示例
下面是相同的演示
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’ 的方法被定义为以字符串为参数。
它基于空格进行拆分。
这些单词被转换为列表并存储在变量中。
它被迭代,并显示在控制台上。
在方法之外,定义一个字符串并显示在控制台上。
通过传递所需参数来调用该方法。
输出显示在控制台上。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

