Getting previous index values ​​of python list items after shuffling

Let's say I have a python list like this:

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

using random.shuffle,

>>> import random
>>> random.shuffle(l)
>>> l
[5, 3, 2, 0, 8, 7, 9, 6, 4, 1]

I have a list above.

How can I get a list of the previous index values ​​of each item in a shuffled list?

+4
source share
5 answers

You can associate each element with its index using enumerate, and then shuffle it.

>>> import random
>>> l = [4, 8, 15, 16, 23, 42]
>>> x = list(enumerate(l))
>>> random.shuffle(x)
>>> indices, l = zip(*x)
>>> l
(4, 8, 15, 23, 42, 16)
>>> indices
(0, 1, 2, 4, 5, 3)

One of the advantages of this approach is that it works regardless of whether it contains lduplicates.

+13
source

If your values ​​are unique, use the method list.index. For example, you can do this:

import random
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
start_l = l[:]
random.shuffle(l)
for elem in l:
    print(elem, '->', start_l.index(elem))

, - .

# gives the same result as above.
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
random.shuffle(l)
for elem in l:
    print(elem, '->', elem)

, . , , . .. , , . , [2, 1, 0] - .

l = list(random.randint(0, 10) for _ in range(10))
l_idx = list(range(len(l)))  # list of indices in l
random.shuffle(l_idx)
for new_idx, old_idx in enumerate(l_idx):
    print(l[old_idx], '@', old_idx, '->', new_idx)
+2

, , :

enumerate , , .

import random

l = [5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
d = {v: i for i, v in enumerate(l)}
print(d) # current state
random.shuffle(l)

The advantage is that you get a O(1)lookup to get your index for whatever value you are looking for.

However, if your list contains duplicates, this answer from Kevin should be called.

+1
source

Create a copy of the original listand shuffle the copy:

>>> import random    
>>> l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l_copy = list(l)  # <-- Creating copy of the list
>>> random.shuffle(l_copy)  # <-- Shuffling the copy
>>> l_copy   # <-- Shuffled copy               
[8, 7, 1, 3, 6, 5, 9, 2, 0, 4]
>>> l   # <-- original list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 
+1
source

More intuitive alternative to other answers:

Shuffle the range of indices and use this to get a shuffled list of source values.

+1
source

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


All Articles