Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中将列表中的项附加到字符串上_Python - Fatal编程技术网

如何在python中将列表中的项附加到字符串上

如何在python中将列表中的项附加到字符串上,python,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] # M

问题如下: “通过组合上面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)


您可以使用简单的添加来组合列表:

options = nouns + verbs + adjs
您可以使用
random.choice()
从列表中选择随机项:

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

您的规范中似乎没有区分词性的内容。因此,您只有一个用于密码目的的单词列表

word_list = nouns + verbs + adjs
现在,您只需从列表中随机获取四项。您应该再次查看
random
文档<代码>示例和
洗牌
在这里很有用。任何一个都可以为您抓取4件物品

pass_words = random.sample(word_list, 4)

最后,只需将所选单词连接起来:

password = ''.join(pass_words)
很少有人会说一句俏皮话

备选方案-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(nouns + verbs + adjs, 4)))
print("".join(random.sample([random.choice(nouns),random.choice(verbs),random.choice(adjs),random.choice(nouns + verbs + adjs)], 4)))