Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to slice the nth column of a list of lists?

I want to slice the the nth column of a list of lists.
e.g.

matrix = [
    ["c","b","a","c"],
    ["d","a","f","d"],
    ["g","h","i","a"]
]

Do i need to transpose the list and then use indices? e.g.

transposed = []
for i in range(len(matrix)+1):
   transposed.append([row[i] for row in matrix])
transposed[1]
>>> ['b','a','h']

or is there a way to use indices directly on the nested list?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I was trying something like:

matrix[:][1]
>>>['d','a','f','d']

but this does not work as I found out.

Thank you

>Solution :

>>> [column[1] for column in matrix]
['b', 'a', 'h']

Is this what you meant?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading