Divide a list with n * n elements into n lists with n elements in each list

I am trying to come up with a function that takes input x and splits a large list with the number of elements x * x into x smaller lists with x elements in each list For example:

big_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] def split_list (x): big_list = pairs (x) small_list = [big_list[0:x] for x in range (x)] 

My conclusion should be:

 [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] 

but I don’t understand what you recommend?

+5
source share
5 answers

You can try the following:

 big_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] def split_list (x): return [big_list[i:i+x] for i in range(0, len(big_list), x)] print(split_list(4)) 

Output:

 [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] 
+7
source

First you want to get the size using the square root, so for a list of size n you will have a mxm matrix with m = n ** 0.5 . First, define your function:

 def square(array): n = len(array) m = int(n ** 0.5) 

Since the list sizes must be integers, we must call int as a result. Then we want to start at 0 and count i to n by m each time, taking m elements starting from i :

 def square(array): n = len(array) m = int(n ** 0.5) result = [] for i in range(0, n, m): result.append(array[i:i + m]) return result 

What is it.

Alternatively, s=lambda a:(lambda m:[a[i*m:i*m+m]for i in range(m)])(int(len(a)**.5))

+2
source

I use this code all the time.

 def chunkify(items, chunk_len): return [items[i:i+chunk_len] for i in range(0,len(items),chunk_len)] 
+2
source

Here is one solution:

 def split_list(big_list, x): list_size = len(big_list) splits = int(list_size / x) return [big_list[k*x:k*x+x] for k in range(splits)] big_list = [i+1 for i in range(16)] print(big_list) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] small_list = split_list(big_list, 4) print(small_list) # [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] small_list = split_list(big_list, 2) print(small_list) # [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14], [15, 16]] small_list = split_list(big_list, 3) print(small_list) # [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]] 
+2
source

why not use numpy :

 >>> import numpy as np >>> big_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] >>> a=np.array(big_list) >>> a array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) >>> n=int(len(big_list)**0.5) >>> a.reshape(n,n) array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]]) 

or simply:

 >>> big_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] >>> n=int(len(big_list)**0.5) >>> new_list=[big_list[i:i+n] for i in range(0, len(big_list), n)] >>> new_list [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] 
+1
source

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


All Articles