How to randomly select an item from a list?

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

提交回复
热议问题