Ergo
Ergo

Reputation: 393

Appending nested list values into a new list

I've got a program that has a nested list which I wish to access and then append to a new list based on a condition. There are three columns in each list and I wish to know how to access them individually. Here's how it looks currently [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]. An example to better explain this would be, if I wanted data from the second column my new list would then look like ['B', 'E', 'H'].

This is what I have so far but I'm currently rather stuck..

n = 0
old_list = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]
new_list = []

for a, sublist in enumerate(old_list):
       for b, column in enumerate(sublist):
              print (a, b, old_list[a][b])
              if n == 0:
                     new_list.append(column[0])
              if n == 1:
                     new_list.append(column[1])
              if n == 2:
                     new_list.append(column[2])

print(new_list)         

My current output..

0 0 A
0 1 B
0 2 C
1 0 D
1 1 E
1 2 F
2 0 G
2 1 H
2 2 I
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']

My desired output ..

n = 0
new_list = ['A', 'D', 'G']

n = 1
new_list = ['B', 'E', 'H']

n = 2
new_list = ['C', 'F', 'I']

Thanks for your help!

Upvotes: 3

Views: 151

Answers (2)

Hai Vu
Hai Vu

Reputation: 40688

Another solution, which does not use the * construction nor zip():

for n in range(3):
    print('n = {}'.format(n))
    new_list = [sublist[n] for sublist in old_list]
    print('new_list = {}'.format(new_list))

Upvotes: 1

jamylak
jamylak

Reputation: 133514

>>> L = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]
>>> columns = list(zip(*L))
>>> columns
[('A', 'D', 'G'), ('B', 'E', 'H'), ('C', 'F', 'I')]
>>> columns[1] # 2nd column
('B', 'E', 'H')

Or if you want each column as a list to modify(since zip returns immutable tuples) then use:

columns = [list(col) for col in zip(*L)]

Upvotes: 6

Related Questions