'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?
I was trying something like:
matrix[:][1]
>>>['d','a','f','d']
but this does not work as I found out.
Thank you
Solution 1:[1]
You could use zip
to transpose your matrix:
list(zip(*matrix))[1]
Output: ('b', 'a', 'h')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mozway |