pythonlist

Appending to 2 dimensional array in python


I am reading Data from CSV file which comes similar to the below matrix/array

b = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

I would like to change the index of every element greater than 1 to a new row in the arraylist

this will make the above array as below

b = [[1,2],[5,6],[9,10],[3,4],[7,8][11,12]]

what i have done in python (but couldn't get the answer)

b = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
c = b
rows = len(b)
columns = len(b[0])
c[4].append(1)
count = 3
for i in  range(rows):
 for j in  range(columns):
     if i > 1:
         for k in columns
             list1 = 
             c.insert(count,list1)
             count = count + 1

Solution

  • Why not just split it into two lists, and then recombine them?

    new_elements = []
    for i in range(len(b)):
        if len(b[i]) > 2:
            new_elements.append(b[i][2:])
        b[i] = b[i][:2]
    b.extend(new_elements)