How do I put data in a two-dimensional array sequentially without duplication?

Question:

I want to put data consisting of a one-dimensional array into a two-dimensional array. I will assume that the number of rows and columns is 5.
The code I tried is as follows.

data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
a = []
for i in range(5):
    a.append([])
    for j in range(5):
        a[i].append(j)
print(a)
# result : [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
# I want this : [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20]]

You don’t have to worry about the last [20].
The important thing is that the row must change without duplicating the data.
I want to solve it, but I can’t think of any way. I ask for your help.

Asked By: skool high

||

Answers:

This should deliever the desired output

data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
a = []
x_i = 5
x_j = 5

    for i in range(x_i):
        a.append([])
        for j in range(x_j):
            a[i].append(i*x_j+j)
    print(a)

Output:

[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]
Answered By: Mole

You could use itertools.groupby with an integer division to create the groups

from itertools import groupby
data = [0, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
grouped_data = [list(v) for k, v in groupby(data, key=lambda x: x//5)]
print(grouped_data)

Output

[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20]]
Answered By: Mortz

There are two issues with the current code.

  1. It doesn’t actually use any of the values from the variable data.
  2. The data does not contain enough items to populate a 5x5 array.

After adding 0 to the beginning of the variable data and using the values from the variable, the code becomes

data = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
a = []
for i in range(5):
    a.append([])
    for j in range(5):
        if i*5+j >= len(data):
            break
        a[i].append(data[i*5+j])
print(a)

The output of the new code will be

[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20]]
Answered By: NikhilMTomy

By using list comprehension…

data = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

columns = 5
rows = 5
result = [data[i * columns: (i + 1) * columns] for i in range(rows)]
print(result)
# [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20]]
Answered By: Jobo Fernandez
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.