How to randomly select an item from a list?

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

    The following code demonstrates if you need to produce the same items. You can also specify how many samples you want to extract.
    The sample method returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples.

    import random as random
    random.seed(0)  # don't use seed function, if you want different results in each run
    print(random.sample(foo,3))  # 3 is the number of sample you want to retrieve
    
    Output:['d', 'e', 'a']
    
    0 讨论(0)
  • 2020-11-21 08:25

    numpy solution: numpy.random.choice

    For this question, it works the same as the accepted answer (import random; random.choice()), but I added it because the programmer may have imported numpy already (like me) & also there are some differences between the two methods that may concern your actual use case.

    import numpy as np    
    np.random.choice(foo) # randomly selects a single item
    

    For reproducibility, you can do:

    np.random.seed(123)
    np.random.choice(foo) # first call will always return 'c'
    

    For samples of one or more items, returned as an array, pass the size argument:

    np.random.choice(foo, 5)          # sample with replacement (default)
    np.random.choice(foo, 5, False)   # sample without replacement
    
    0 讨论(0)
  • 2020-11-21 08:33

    This is the code with a variable that defines the random index:

    import random
    
    foo = ['a', 'b', 'c', 'd', 'e']
    randomindex = random.randint(0,len(foo)-1) 
    print (foo[randomindex])
    ## print (randomindex)
    

    This is the code without the variable:

    import random
    
    foo = ['a', 'b', 'c', 'd', 'e']
    print (foo[random.randint(0,len(foo)-1)])
    

    And this is the code in the shortest and smartest way to do it:

    import random
    
    foo = ['a', 'b', 'c', 'd', 'e']
    print(random.choice(foo))
    

    (python 2.7)

    0 讨论(0)
  • 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([])
    
    0 讨论(0)
  • 2020-11-21 08:34

    We can also do this using randint.

    from random import randint
    l= ['a','b','c']
    
    def get_rand_element(l):
        if l:
            return l[randint(0,len(l)-1)]
        else:
            return None
    
    get_rand_element(l)
    
    0 讨论(0)
  • 2020-11-21 08:35

    Use random.choice()

    import random
    
    foo = ['a', 'b', 'c', 'd', 'e']
    print(random.choice(foo))
    

    For cryptographically secure random choices (e.g. for generating a passphrase from a wordlist) use secrets.choice()

    import secrets
    
    foo = ['battery', 'correct', 'horse', 'staple']
    print(secrets.choice(foo))
    

    secrets is new in Python 3.6, on older versions of Python you can use the random.SystemRandom class:

    import random
    
    secure_random = random.SystemRandom()
    print(secure_random.choice(foo))
    
    0 讨论(0)
提交回复
热议问题