How to randomly select an item from a list?

后端 未结 15 1345
伪装坚强ぢ
伪装坚强ぢ 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

提交回复
热议问题