如何 select 从集合中随机抽取特定数量的元素?

How to select a specific number of random elements from a set?

我有一组 9 个元素,我想编写一个程序提示用户输入一个整数 n,然后显示从我的集合中随机选择的 n 个元素。

这是我试过的:

import random

def main():    
    best_of = eval(input("How many maps do you want to choose? : "))

    choices = ["Arkansas", "Manchuria", "Bengal", "Baja California", "Tibet", "Indonesia", "Cascade Range", "Hudson Bay", "High Plains"]

    random_choice = random.choice(choices)

    for i in range(bes_of):    
        print(random_choice)

main()

使用random.sample() function选择n个不重复的随机元素:

sampled = random.sample(choices, best_of)
for choice in sampled:
    print(choice)

如果您只需要来自用户的整数,请不要使用 eval();坚持使用 int() 代替:

best_of = int(input("How many maps do you want to choose? : "))

eval() 给你的比你预料的要多;它执行任何有效的Python表达式,让用户可以用你的程序做任何他们想做的事情。

您需要在 for 循环中调用 random.choice() 方法,以便打印 n 个随机元素。

import random

def main():    
    best_of = input("How many maps do you want to choose? : ")

    choices = ["Arkansas", "Manchuria", "Bengal", "Baja California", "Tibet", "Indonesia", "Cascade Range", "Hudson Bay", "High Plains"]

    for i in range(int(best_of)):    
        random_choice = random.choice(choices)
        print(random_choice)

main()