Python. Extract random object from a list

6

The problem is that I have a list "l" of which I want to select a random item several times without repeating it, and I do not know how to do it. Any suggestions?

import random

l = ["a", "b", "c", "d"]

sel1 = random.choice(l)

That's fine, but now I want to define a "sel2" that is a random element of "l" but different of "sel1" . And so we can continue defining a "sel3" different from "sel1" and "sel2" .

Thanks in advance =)

    
asked by 256 20.06.2016 в 01:54
source

4 answers

3

Instead of randomly choosing element by element, make a random arrangement of the entire list:

l2 = l[:]  # copia de la lista
random.shuffle(l2)

sel1, sel2, sel3 = l2[:3]

or more simple, use random.sample :

sel1, sel2, sel3 = random.sample(l, 3)
    
answered by 20.06.2016 в 02:24
2

You could give another approach to your problem: why not mess up the list and take each element out of it?

The shuffle function allows you to clutter the elements in a list. Look at this example:

from random import shuffle

list = ["a", "b", "c", "d"]
shuffle(list) # list -> ["c", "a", "d", "b"]

sel1 = list[0] # "c"
sel2 = list[1] # "a"
....

Greetings.

    
answered by 20.06.2016 в 02:21
0

You can try this little function:

import random
def random_sin_repetir(lista):
    for _ in range(0,len(lista)):
        result = random.choice(lista)
        yield result
        lista.remove(result)

You can check the results with:

lista = ["a", "b", "c", "d"]
[i for i in random_sin_repetir(lista)]
  
    

['a', 'c', 'b', 'd']

  
lista = ["a", "b", "c", "d"]
[i for i in random_sin_repetir(lista)]
  
    

['b', 'd', 'c', 'a']

  
    
answered by 22.06.2016 в 11:08
0

Everything you propose can be a good solution if the elements contained in the list are not repeated, if the elements could be defined several times within the list we would initially have to find what the different elements are.

A possible solution to eliminate repeated elements could be:

lista_original = list(set(lista_original))

Other possible ways: link

    
answered by 17.08.2016 в 10:02