簡體   English   中英

列表的排列

[英]Permutations of a list

這次我嘗試輸入一個句子,例如: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 沒用,但我嘗試使用它

我正在打印置換而不是 i :(

感謝 Perplexabot 在評論中的洞察力。

調用排列運算符時,必須使用迭代器來實例化值。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM