For example, as to
[1 2 3 4 5 6]
Shuffle the data while keeping data blocks(including 2 data) as before. And we'll acquire:
[3 4 1 2 5 6]
Any way in Python to do this?
A straightforward way to do this is using the following three steps:
So:
import random
# Import data
data = [1,2,3,4,5,6]
blocksize = 2
# Create blocks
blocks = [data[i:i+blocksize] for i in range(0,len(data),blocksize)]
# shuffle the blocks
random.shuffle(blocks)
# concatenate the shuffled blocks
data[:] = [b for bs in blocks for b in bs]
If you do not want to store the data back in data
, you can simply use:
data = [b for bs in blocks for b in bs]
For this data I obtained:
>>> data
[3, 4, 1, 2, 5, 6]
a second time:
>>> data
[5, 6, 1, 2, 3, 4]
You can use the random
module and call the function random.shuffle()
- this will shuffle every element in your list, so break your list into sublists before shuffling
import random, itertools
mylist = [1, 2, 3, 4, 5, 6]
blocks = [mylist[x:x+2] for x in range(0, len(mylist), 2)]
random.shuffle(blocks)
list(itertools.chain.from_iterable(blocks))
>> [3, 4, 1, 2, 5, 6]
Somebody asked for a solution using numpy:
>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6])
>>> np.random.shuffle(a.reshape((-1, 2)))
>>> a
array([5, 6, 3, 4, 1, 2])
This shuffles the reshaped view in place, but a keeps its original dimensions, so there's no need to reshape back.
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