Jak losowo wybrać przedmiot z listy?

Załóżmy, że mam następującą listę:

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

Jaki jest najprostszy sposób, aby pobrać element losowo z tej listy?

Author: martineau, 2008-11-20

13 answers

Użycie random.choice:

import random

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

Do bezpiecznych kryptograficznie wyborów losowych( np. do generowania hasła z listy słów), użyj random.SystemRandom klasa:

import random

foo = ['battery', 'correct', 'horse', 'staple']
secure_random = random.SystemRandom()
print(secure_random.choice(foo))
 2206
Author: Pēteris Caune,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-06 13:14:17

Jeśli potrzebujesz również indeksu, użyj random.randrange

from random import randrange
random_index = randrange(len(foo))
print(foo[random_index])
 133
Author: Juampi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-18 04:02:08

Jeśli chcesz losowo wybrać więcej niż jeden element z listy lub wybrać element z zestawu, zalecam użycie random.sample.

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] 

Jeśli wyciągasz tylko pojedynczy element z listy, Wybór jest mniej niezgrabny, ponieważ użycie sample miałoby składnię random.sample(some_list, 1)[0] zamiast random.choice(some_list).

Niestety, wybór działa tylko dla pojedynczego wyjścia z sekwencji (takich jak listy lub krotki). Chociaż random.choice(tuple(some_set)) może być opcją uzyskania pojedynczego elementu z zestawu.

 116
Author: Paul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-11 17:54:31

Od wersji Python 3.6 możesz używać secrets moduł, który jest preferowany do random moduł do zastosowań kryptograficznych lub zabezpieczających.

Aby wydrukować losowy element z listy:

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

Aby wydrukować losowy indeks:

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

Aby uzyskać szczegółowe informacje, zobaczPEP 506 .

 30
Author: Chris_Rands,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-06 12:06:21

Proponuję skrypt do usuwania losowo wybranych elementów z listy, dopóki nie będzie pusta:

Utrzymuj set i usuń losowo wybrany element (z choice), dopóki lista nie będzie pusta.

s=set(range(1,6))
import random

while len(s)>0:
  s.remove(random.choice(list(s)))
  print(s)

Trzy biegi dają trzy różne odpowiedzi:

>>> 
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([])
 28
Author: octoback,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-24 10:56:23

Jest to kod ze zmienną określającą indeks losowy:

import random

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

Jest to kod bez zmiennej:

import random

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

I to jest kod w najkrótszy i najmądrzejszy sposób, aby to zrobić:

import random

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

(python 2.7)

 7
Author: Liam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-25 16:56:16
foo = ['a', 'b', 'c', 'd', 'e']
number_of_samples = 1

W Pythonie 2:

random_items = random.sample(population=foo, k=number_of_samples)

W Pythonie 3:

random_items = random.choices(population=foo, k=number_of_samples)
 7
Author: Fardin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-29 16:40:11

Jeśli potrzebujesz indeksu po prostu użyj:

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

Losowe.wybór robi to samo:)

 6
Author: Janek Olszak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-23 22:06:36

Jak losowo wybrać przedmiot z listy?

Załóżmy, że mam następującą listę:

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

Jaki jest najprostszy sposób, aby pobrać element losowo z tej listy?

Jeśli chcesz zbliżyć się do naprawdę losowego, proponuję użyć SystemRandom obiektu z modułu random z metodą choice:

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

A teraz:

>>> 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'

Jeśli chcesz mieć deterministyczny wybór pseudorandomu, użyj funkcji choice (która jest w rzeczywistości metoda związana na obiekcie Random):

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

Wydaje się to przypadkowe, ale tak naprawdę nie jest, co możemy zobaczyć, jeśli będziemy go ponownie przesyłać wielokrotnie:

>>> 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')
 5
Author: Aaron Hall,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-23 22:22:13

Możemy to również zrobić za pomocą randinta.

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)
 3
Author: Abdul Majeed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-06 19:00:48

numpy rozwiązanie: numpy.random.choice

Na to pytanie działa tak samo jak zaakceptowana odpowiedź (import random; random.choice()), ale dodałem ją, ponieważ programista mógł już zaimportować numpy (Jak ja) istnieją również pewne różnice między dwiema metodami , które mogą dotyczyć Twojego rzeczywistego przypadku użycia.

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

Dla odtwarzalności, można zrobić:

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

Dla próbek jednego lub więcej elementów, zwracanych jako array, podaj argument size:

np.random.choice(foo, 5)          # sample with replacement (default)
np.random.choice(foo, 5, False)   # sample without replacement
 2
Author: C8H10N4O2,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-17 16:27:49

Zrobiłem to, aby to zadziałało:

import random
pick = ['Random','Random1','Random2','Random3']
print  (pick[int(random.random() * len(pick))])
 -8
Author: Captain BudderChunk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-11 17:11:32
import random_necessary
pick = ['Miss','Mrs','MiSs','Miss']
print  pick [int(random_necessary.random_necessary() * len(pick))]

Mam nadzieję, że to rozwiązanie okaże się pomocne.

 -20
Author: phani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-11 17:39:50