如何从一组中选择特定数量的随机元素?

时间:2015-06-04 21:39:25

标签: python python-3.x random

我有一组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()

2 个答案:

答案 0 :(得分:3)

使用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表达式,让用户随你的程序做任何他们想做的事情。

答案 1 :(得分:1)

您需要在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()