首页 > 解决方案 > 列表的排列

问题描述

这次我尝试输入一个句子,例如: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 没用,但我尝试使用它

标签: pythonpermutation

解决方案


调用排列运算符时,您必须使用迭代器来实例化这些值。

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

推荐阅读