gpt4 book ai didi

python - 列表的排列

转载 作者:行者123 更新时间:2023-12-04 10:56:26 24 4
gpt4 key购买 nike

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

关于python - 列表的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59147311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com