0

I've got a program that is designed to access a nested list and then print values from a certain column in each sublist. My problem being, I don't know how to edit this to provide more freedom with what values I wish to print out. This is how it looks currently ..

column = [['A', 'A', 'B'], ['B', 'A', ''], ['', '', 'B']]
n = 1
columns = list(zip(*column))
print(list(columns[n]))

>>> ['A', 'A', '']

I was wondering if it was possible to modify this so I could then, for example, print out the first item in sublist1, second item in sublist2 and third item in sublist 3. Giving me something like..

>>> ['A', 'A', 'B']

My original attempt at this was to to run a for loop and then try appending values through into a new list but I can't figure it out due to my novice knowledge.

Cheers in advance for the help!

3
Contributors
2
Replies
27
Views
4 Years
Discussion Span
Last Post by pyTony
1

First of all, unzip step doesn't really help you. You can get the ith element of each list with list comprehension:
list=[a[i] for a in column] for a given i.

To get some other set of elements as you describe will require looping through the number of elements and taking each desired element explicitly.

Edited by rrashkin

1

Use list comprehension with enumerate:

>>> column = [['A', 'A', 'B'], ['B', 'A', ''], ['', '', 'B']]
>>> print [item[ind] for ind, item in enumerate(column)]
['A', 'A', 'B']
>>> 
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.