如何将列表中的项目附加到Python中的字符串中

问题如下:“通过组合上面 3 个列表中的 4 个单词来创建密码。打印密码”在该问题中,组合意味着将单词连接在一起。我的代码打印在下面,但我很好奇如何优化它。我确信我不需要将密码列出来。请随意包含我可以做的任何其他优化。谢谢!


import itertools

import random


nouns =[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 adjs


options = 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)


长风秋雁
浏览 98回答 3
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

很少有一个班轮。选项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)))这样的衬里有很多,性能上略有差异。

四季花海

您可以使用简单的加法来组合列表:options = nouns + verbs + adjs您可以使用random.choice()从列表中选择随机项目:for _ in range (4):     password.append(random.choice(options))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python