問題如下:“通過組合上面 3 個列表中的 4 個單詞來創建密碼。打印密碼”在該問題中,組合意味著將單詞連接在一起。我的代碼打印在下面,但我很好奇如何優化它。我確信我不需要將密碼列出來。請隨意包含我可以做的任何其他優化。謝謝!import itertoolsimport randomnouns =[A large list of strings]verbs = [A large list of strings]adjs = [A large list of strings]# Make a four word password by combining words from the list of nouns, verbs and adjsoptions = list(itertools.chain(nouns, verbs, adjs))password = []for _ in range (4): password.append(options[random.randint(0,len(options)-1)]) password = "".join(password) print(password)
3 回答

泛舟湖上清波郎朗
TA貢獻1818條經驗 獲得超3個贊
您的規范中似乎沒有任何內容可以區分詞性。因此,您只有一個用于密碼目的的單詞列表。
word_list = nouns + verbs + adjs
現在您只需從列表中隨機選取四個項目即可。您應該random
再次查看文檔。 sample
并且shuffle
在這里很有用。任何人都可以為您搶到 4 件物品。
pass_words = random.sample(word_list, 4)
或者
random.shuffle(word_list) pass_words = word_list[:4]
最后,簡單地連接所選單詞:
password = ''.join(pass_words)

慕斯709654
TA貢獻1840條經驗 獲得超5個贊
很少有一個班輪。
選項1 :
print("".join(random.choice(nouns + verbs + adjs) for _ in range(4)))
選項-2:
print("".join(random.sample(nouns + verbs + adjs, 4)))
選項 3(如果您想要至少一項來自動詞、名詞和形容詞的條目):
print("".join(random.sample([random.choice(nouns),random.choice(verbs),random.choice(adjs),random.choice(nouns + verbs + adjs)], 4)))
這樣的襯里有很多,性能上略有差異。

四季花海
TA貢獻1811條經驗 獲得超5個贊
您可以使用簡單的加法來組合列表:
options = nouns + verbs + adjs
您可以使用random.choice()
從列表中選擇隨機項目:
for _ in range (4): password.append(random.choice(options))
添加回答
舉報
0/150
提交
取消