lis的排列

2024-10-03 21:24:15 发布

您现在位置:Python中文网/ 问答频道 /正文

这次我试着输入一个句子,比如:helloworld!,通过.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没用,但我试过用它


Tags: 代码textinforinput错误ls句子
2条回答

我正在打印置换,而不是我:(

感谢你在评论中的洞察力。你知道吗

调用置换运算符时,必须使用迭代器来实例化这些值。你知道吗

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

相关问题 更多 >