Is there a function in Python that shuffles data with data blocks?

For example, regarding

[1 2 3 4 5 6] 

Shuffle data while saving data blocks (including 2 data), as before. And we get:

 [3 4 1 2 5 6] 

How to do this in Python?

+5
source share
6 answers

An easy way to do this is to use the following three steps:

  • create blocks (2d list);
  • shuffle this list; and
  • merge these lists again.

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 save data in data , you can simply use:

 data = [b for bs in blocks for b in bs] 

For this data, I received:

 >>> data [3, 4, 1, 2, 5, 6] 

second time:

 >>> data [5, 6, 1, 2, 3, 4] 
+7
source

You can use the random module and call the random.shuffle() function - this will shuffle each item in your list, so break the list in the lists 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] 
+3
source

Maximum use of standard methods:

 >>> import random, itertools >>> a [1, 2, 3, 4, 5, 6] # group elements by 2 >>> grouped = list(zip(*[iter(a)]*2)) >>> grouped [(1, 2), (3, 4), (5, 6)] # shuffle groups >>> random.shuffle(grouped) >>> grouped [(3, 4), (1, 2), (5, 6)] # flatten groups to list >>> list(itertools.chain.from_iterable(grouped)) [3, 4, 1, 2, 5, 6] 
+2
source

Easy way

 import random data = [1,2,3,4,5,6] temp = range(len(data)/2) random.shuffle(temp) data_c = data[:] for i, j in enumerate(temp): if not i == j: data_c[i*2],data_c[(i*2)+1] = data[j*2],data[(j*2)+1] print(data_c) 

Output

 [1, 2, 5, 6, 3, 4] 
+2
source

There are no built-in functions, but you can write a little helper to do this for you:

1- create blocks
2- Shuffle them
3- smooth the blocks and return the resulting shuffled sequence.

  import random def shuffle_by_blocks(seq, blocksize): blocks = [seq[idx*blocksize: (idx+1)*blocksize] for idx in range(len(seq)//blocksize)] random.shuffle(blocks) return [elt for block in blocks for elt in block ] shuffle_by_blocks([1,2,3,4,5,6], 2) 

output sample:

 [1, 2, 5, 6, 3, 4] 
+1
source

Someone 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 resized view in place, but a retains its original size, so there is no need to reformat it back.

0
source

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


All Articles