生成随机名称列表-Python

2024-05-22 00:49:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个名字列表,每个名字都不一样。这是我现在的代码,但它所做的一切创建了同一名称的多个实例。

import random

first_names=('John','Andy','Joe')
last_names=('Johnson','Smith','Williams')

full_name=random.choice(first_names)+" "+random.choice(last_names)

group=full_name*3

例如,这将显示为:

John Smith
John Smith
John Smith

但我想要这样的东西:

John Williams
Andy Johnson
Joe Johnson

Tags: name列表namesrandom名字johnfullfirst
3条回答

这是因为您生成了一个名称,然后复制了三次。

如果你想要三个不同的名字,那么循环三次你的选择程序:

group = []
for i in range(3):
    full_name=random.choice(first_names)+" "+random.choice(last_names)
    group.append(full_name)
 #assuming he wants at least some kind of seperator between the names.
 group_string = ", ".join(group)

顺便问一句,您真的希望都是刚刚连接的名称吗?

你只是在这里复制你的字符串。随机只发生一次。

改为在生成器理解中进行,并将结果与空格连接起来:

import random

first_names=('John','Andy','Joe')
last_names=('Johnson','Smith','Williams')

group=" ".join(random.choice(first_names)+" "+random.choice(last_names) for _ in range(3))


print(group)

输出:

Joe Williams Joe Johnson Joe Smith

您所做的是对字符串使用*3,这意味着它将复制该字符串三次。

要做你想做的事,你必须为名字和姓氏调用random.choice三次。

full_name1 = random.choice(first_names)+" "+random.choice(last_names)
full_name2 = random.choice(first_names)+" "+random.choice(last_names)
full_name3 = random.choice(first_names)+" "+random.choice(last_names)

group = full_name1 + " " + full_name2 + " " + full_name3

也可以在for循环中执行此操作,以避免重复代码。

相关问题 更多 >