1

How to create 2D list from 1D list with given row and cols?

Given:

sample_list=[5, 2, 3, 4, 1, 6, 1, 6, 7, 2, 3]

row=2
cols=4

It should return this:

[[5, 2, 3, 4],[1, 6, 1, 6]]

I don't need other numbers = 7, 2, 3. I just want a list that has row and cols which user gives. My solution does not return what i want,

My solution:

def 1D_to_2D(sample_list, row, cols):
    return [sample_list[i:i+cols] for i in range(0, len(sample_list), rows)]

returns:

[[5, 2, 3, 4], [3, 4, 1, 6], [1, 6, 1, 6], [1, 6, 7, 2], [7, 2, 3], [3]]

Anyone can help?

3 Answers3

1

Just slice your list using a list comprehension with range and a step of cols (not rows as you used), and limit the number of items using external slicing with rows:

sample_list=[5, 2, 3, 4, 1, 6, 1, 6, 7, 2, 3]
rows=2
cols=4

result = [sample_list[x:x+cols] for x in range(0,len(sample_list),cols)][:rows]

result:

[[5, 2, 3, 4], [1, 6, 1, 6]]
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1
def D_to_2D(sample_list, rows, cols):
    return [sample_list[cols*i: cols*(i+1)] for i in range(rows)]

>>> D_to_2D([5, 2, 3, 4, 1, 6, 1, 6, 7, 2, 3], 2, 4)
[[5, 2, 3, 4], [1, 6, 1, 6]]
Huang
  • 599
  • 2
  • 6
0
f = lambda x, row, cols: [x[i:i+cols] for i in range(0, cols*row, cols)]
f(x, row, cols)
Reza
  • 141
  • 1
  • 12