So, i want to convert a one dim list into a 2 dim one : The first list have a lenght of n² . The second one must be n*n. How to do that without numpy ? Thanks in advance
CodePudding user response:
There are many ways to organize a flat list into a "square" nested list depending on the counting order. Here the most natural example:
flat_list = list(range(16))
dim = int(len(flat_list)**.5)
square_list = [flat_list[dim*i: dim*(i 1)] for i in range(dim)]
print(square_list)
# [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]
Remark: the list is assumed to have n**2
elements as mentioned in the question otherwise add a conditional check with a proper exception handler