Home > Software design >  2 dimensional list in Python, trying to move data from one list to another
2 dimensional list in Python, trying to move data from one list to another

Time:03-14

I am stuck on a 2D list data transfer problem. In a nutshell, I have 2D list like this:

listA = [['Green', 11455519, 23, 11661206], ['Blue', 7000039, 42, 6690388]]

It has 20 or more rows that follow the same pattern, I just plucked out two. I want to transfer the data over to a new list, where, as an example, I would just select some of the columns, so that it would look like this:

listB = [['Green', 23 ], ['Blue', 42]]

Instead I am getting this:

listB = [['Green', 23 ,'Blue', 42],[]]

i.e. all elements are falling into only the first row. So for my actual example, that means all the elements piled in, in that pattern and fashion, in the first row, and then 20 [] empty rows afterwards in that listB. I am using append and nested for statements to no avail.

Can I please ask for some help?

Thanks!

J

CodePudding user response:

listA = [['Green', 11455519, 23, 11661206], ['Blue', 7000039, 42, 6690388]]
[x[0:4:2] for x in listA]

Output

Out[5]: [['Green', 23], ['Blue', 42]]

CodePudding user response:

With a list comprehension, you can select for each row the items you want in your new list. In this example I select the items ẁith indices 0 and 2:

listB = [[x[0],x[2]] for x in listA]

print(listB)

Output:

[['Green', 23], ['Blue', 42]]
  • Related