How to randomly select an item from a list?

后端 未结 15 1266
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 07:49

Assume I have the following list:

foo = [\'a\', \'b\', \'c\', \'d\', \'e\']

What is the simplest way to retrieve an item at random from thi

相关标签:
15条回答
  • 2020-11-21 08:35

    Random item selection:

    import random
    
    my_list = [1, 2, 3, 4, 5]
    num_selections = 2
    
    new_list = random.sample(my_list, num_selections)
    

    To preserve the order of the list, you could do:

    randIndex = random.sample(range(len(my_list)), n_selections)
    randIndex.sort()
    new_list = [my_list[i] for i in randIndex]
    

    Duplicate of https://stackoverflow.com/a/49682832/4383027

    0 讨论(0)
  • 2020-11-21 08:37
    foo = ['a', 'b', 'c', 'd', 'e']
    number_of_samples = 1
    

    In python 2:

    random_items = random.sample(population=foo, k=number_of_samples)
    

    In python 3:

    random_items = random.choices(population=foo, k=number_of_samples)
    
    0 讨论(0)
  • 2020-11-21 08:37

    You could just:

    from random import randint
    
    foo = ["a", "b", "c", "d", "e"]
    
    print(foo[randint(0,4)])
    
    0 讨论(0)
提交回复
热议问题