How to randomly select an item from a list?

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

    I propose a script for removing randomly picked up items off a list until it is empty:

    Maintain a set and remove randomly picked up element (with choice) until list is empty.

    s=set(range(1,6))
    import random
    
    while len(s)>0:
      s.remove(random.choice(list(s)))
      print(s)
    

    Three runs give three different answers:

    >>> 
    set([1, 3, 4, 5])
    set([3, 4, 5])
    set([3, 4])
    set([4])
    set([])
    >>> 
    set([1, 2, 3, 5])
    set([2, 3, 5])
    set([2, 3])
    set([2])
    set([])
    
    >>> 
    set([1, 2, 3, 5])
    set([1, 2, 3])
    set([1, 2])
    set([1])
    set([])
    

提交回复
热议问题