如何使用列表生成随机组名

how do I generate random group names using lists

我想不通我的错误。有人可以帮助我吗?

我们应该在函数之外创建列表。然后在函数内创建一个空列表。我们应该 return 9 个不同的名字。

    first_names = ["Gabriel", "Reinhard", "Siebren"]
    last_names = ["Colomar", "Chase", "Vaswani"]

    def name_generator(first_names, last_names):
        full_name= ()

    import random

    for _ in range(9):
        full_name=random.choice(first_names)+" "+random.choice(last_names)
        full_name.append(full_name)
    group_string = ", ".join(full_name) 

问题是您使用变量 full_name 两次:一次作为字符串存储新名称,另一次作为列表。这更接近你想要的:

    import random

    first_names = ["Gabriel", "Reinhard", "Siebren"]
    last_names = ["Colomar", "Chase", "Vaswani"]
    full_names = []

    for _ in range(9):
        new_name=random.choice(first_names)+" "+random.choice(last_names)
        full_names.append(new_name)
    group_string = ", ".join(full_names) 

我会注意到,我可能也会使用 full_names 作为变量名称的复数形式,因为它是多个事物的列表。

这会列出所有可能的全名,然后从尚未使用的全名中一一挑选。

remaining = [(a,b) for a in range(len(first_names)) for b in range(len(last_names))]

full_name = []
while len(remaining)>0:
    (a,b) = random.choice(remaining)
    full_name.append(first_names[a] + " " + last_names[b])
    remaining.remove((a,b))