列表的排列

时间:2019-12-02 22:03:43

标签: python permutation

这一次,我试图输入像这样的句子:世界您好! ,通过.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没有用,但是我尝试使用它

2 个答案:

答案 0 :(得分:1)

调用置换运算符时,必须使用迭代器来实例化值。

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

答案 1 :(得分:0)

我正在打印排列的而不是i:(

感谢Perplexabot在评论中的洞察力。