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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With