Home > Enterprise >  Fill Matrix Rows in Python
Fill Matrix Rows in Python

Time:11-11

Let's say we have a nested list in Python. AKA a matrix, and we have a list consisting of elements, lets say li = [1, 2, 3, 4, 5, 6]. I want to insert two elements in matrix rows, resulting matrix = [ [1,2] [3,4], [5,6] ]. How can this be done ? Thanks!

b = [[]]
c = [1, 2, 3, 4, 5, 6]

for i in range(len(c)):
    for j in range(2):
        b[i].append(c[i])

print(b)

CodePudding user response:

How can this be done ?

  • split the list with slices
    a[0:2],a[2:4],a[4:6]
  • append each of those to an empty list
  • or construct a list with those slices as the items

CodePudding user response:

You can do it just like this:

c = [1, 2, 3, 4, 5, 6]
b = []
fixed_c = []
for i in range(len(c)   1):
    if len(b) < 2 :
        b.append(c[i])
    elif len(b) == 2 and i != len(c):
        fixed_c.append(b)
        b = []
        b.append(c[i])
    else:
        fixed_c.append(b)
        
print(fixed_c)
  • Related