亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將列表中的項目附加到Python中的字符串中

如何將列表中的項目附加到Python中的字符串中

長風秋雁 2023-09-26 15:03:59
問題如下:“通過組合上面 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)


查看完整回答
反對 回復 2023-09-26
?
慕斯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)))

這樣的襯里有很多,性能上略有差異。


查看完整回答
反對 回復 2023-09-26
?
四季花海

TA貢獻1811條經驗 獲得超5個贊

您可以使用簡單的加法來組合列表:

options = nouns + verbs + adjs

您可以使用random.choice()從列表中選擇隨機項目:

for _ in range (4):
    password.append(random.choice(options))


查看完整回答
反對 回復 2023-09-26
  • 3 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號