# 如何从列表中随机select一个项目？

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

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

` `import random foo = ['battery', 'correct', 'horse', 'staple'] secure_random = random.SystemRandom() print(secure_random.choice(foo))` `

` `foo = ['a', 'b', 'c', 'd', 'e'] from random import randrange random_index = randrange(0,len(foo)) print foo[random_index]` `

` `import random group_of_items = {1, 2, 3, 4} # a sequence or set will work here. num_to_select = 2 # set the number to select here. list_of_random_items = random.sample(group_of_items, num_to_select) first_random_item = list_of_random_items[0] second_random_item = list_of_random_items[1]` `

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

` `>>> 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([])` `

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

` `print(secrets.randbelow(len(foo)))` `

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

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

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

（python 2.7）

` `import random foo = ['a', 'b', 'c', 'd', 'e'] print int(random.random() * len(foo)) print foo[int(random.random() * len(foo))]` `

random.choice也是这样:)

` `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)` `

## 如何从列表中随机select一个项目？

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

` `>>> import random >>> sr = random.SystemRandom() >>> foo = list('abcde') >>> foo ['a', 'b', 'c', 'd', 'e']` `

` `>>> sr.choice(foo) 'd' >>> sr.choice(foo) 'e' >>> sr.choice(foo) 'a' >>> sr.choice(foo) 'b' >>> sr.choice(foo) 'a' >>> sr.choice(foo) 'c' >>> sr.choice(foo) 'c'` `

` `>>> random.choice <bound method Random.choice of <random.Random object at 0x800c1034>>` `

` `>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo) ('d', 'a', 'b') >>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo) ('d', 'a', 'b') >>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo) ('d', 'a', 'b') >>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo) ('d', 'a', 'b') >>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo) ('d', 'a', 'b')` `

` `import random pick = ['Random','Random1','Random2','Random3'] print (pick[int(random.random() * len(pick))])` `
` `import random_necessary pick = ['Miss','Mrs','MiSs','Miss'] print pick [int(random_necessary.random_necessary() * len(pick))]` `