python - 列表的排列
问题描述
这次我尝试输入一个句子,例如:Hello World!,通过 .split(" ") 将其拆分并打印所有可能的组合,但代码会排除错误。
x = str(input("Text?"))
x = x.split(" ")
print(x)
ls = []
for i in x:
ls.append(i)
print(ls)
permutated = permutations(ls,len(ls))
for i in permutated:
print(permutated)
ls 没用,但我尝试使用它
解决方案
调用排列运算符时,您必须使用迭代器来实例化这些值。
import itertools
x = "Hello world this is a planet"
x = x.split()
all_combos = list(itertools.permutations(x, r=len(x)))
# print(f'Your data has {len(all_combos)} possible combinations')
# Your data has 720 possible combinations
如果您想更进一步并评估所有组合,不限于输入中的单词数:
all_combos2 = []
for i in range(1, len(x)+1):
all_combos2 += list(itertools.permutations(x, i))
print(f'Your data has {len(all_combos2)} possible combinations')
# Your data has 1956 possible combinations
推荐阅读
- javascript - Visual Studio Code 不允许我调试我编写的特定代码
- c# - 带有 Blazor 的 ASP.NET Core:无法确定 cookie 身份验证
- java - JSP 抛出空指针异常
- php - 如何在 PHP 中运行 websocket 服务器时运行计算?
- php - 有没有办法在 php/Laravel 中不提示下载文件
- css - 如何使元素前后的倾斜结尾?
- php - 配置 Codeigniter-3.1.10 以使用 mongodb
- max - SSRS(报表生成器)来自同一数据集的最小值和最大值
- php - 警告:在第 234 行遇到一个非数字值
- php - MyISAM 比赛条件 / LOCK TABLES