Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting previous index values of a python list items after shuffling

Tags:

python

Let's say I have such a python list:

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

by using random.shuffle,

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

I am having the above list.

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

like image 226
yusuf Avatar asked Nov 30 '22 09:11

yusuf


1 Answers

You could pair each item with its index using enumerate, then shuffle that.

>>> 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 advantage of this approach is that it works regardless of whether l contains duplicates.

like image 126
Kevin Avatar answered Dec 06 '22 22:12

Kevin