-1

i have a added data from a csv file into a list. But now is the list build like this:

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

How to transform a list in a 2D list like this:

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

lcsv=[]
newldata=[]

for column
    newldata.append(
    for row in lcsv:
        newldata.append(lcsv[1*row][0])
        newldata.append(lcsv[1*row][1])
        newldata.append(lcsv[1*row][2])
    )

what's wrong?

DK Germany
  • 11
  • 6

1 Answers1

1

You can use a list comprehension combined with the range function:

l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
l = [l[i:i+3] for i in range(0, len(l), 3)]
>>> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

The range function generates the numbers [0, 6, 9, ..., len(l)], therefore the statement l[i:i+3] inside the list comprehension will put the sublists l[0:3], l[3:6], and l[6:9] into a new list.

Jay Mody
  • 3,727
  • 1
  • 11
  • 27