How to select random items from a list, avoiding selecting the same item in a row

I want to iterate over a list with random values. However, I want the item that was selected to be removed from the list for the next test, so that I can avoid selecting the same item in the row; but it should be added back after.

please help me show this with this simple example. thank you

import random
    l = [1,2,3,4,5,6,7,8]
    for i in l:
        print random.choice(l)
+4
source share
4 answers

Both work also for a list of non-ideal elements:

def choice_without_repetition(lst):
    prev = None
    while True:
        i = random.randrange(len(lst))
        if i != prev:
            yield lst[i]
            prev = i

or

def choice_without_repetition(lst):
    i = 0
    while True:
        i = (i + random.randrange(1, len(lst))) % len(lst)
        yield lst[i]

Using:

lst = [1,2,3,4,5,6,7,8]
for x in choice_without_repetition(lst):
    print x
+8
source

. , , , :

import random

l = [1,2,3,4,5,6,7,8]
random.shuffle(l)
for element in l:
    print(element)
l = sorted(l)
print(l)

3
2
8
6
7
5
1
4
[1, 2, 3, 4, 5, 6, 7, 8]
+1

, :

import random

def choice_no_repeat(lst):
    random.shuffle(lst)
    last = lst[0]
    lst.pop(0)
    yield last
    while True:
        random.shuffle(lst)
        last, lst[0] = lst[0], last
        yield last

choice = choice_no_repeat([1, 2, 3, 4, 5, 6, 7, 8])
for _ in range(10):
    print(next(choice))

:

1
6
1
3
8
7
4
7
1
8
+1

EDIT: , : M N.

numpy, np.random.choice, , :

1-D

replace=False , . , :

np.random.choice([1,2,3,4,5,6,7,8], 8, replace=False)
0

Source: https://habr.com/ru/post/1624137/


All Articles