Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a column in an matrix without numpy

I'm really new to programming, so I apologize if this is a really simple question, but i've been trying to print the first column in a matrix without the use of numpy, however it prints like so:

matrix = \
[[0, 1],
 [3, 7],
 [9, 4],
 [10, 3]]

print matrix[0:3][0]
[0, 1] 

I've also tried:

print matrix[:][0]
[0, 1]

print matrix[:3]
[[0, 1], [3, 7], [9, 4]]

print matrix[:3][0]
[[0, 1], [3, 7], [9, 4]]

The answer I'm trying to achieve is:

print matrix[code]
0, 3, 9, 10

or similar.

like image 384
Chucky Chan Avatar asked Oct 15 '25 19:10

Chucky Chan


1 Answers

What you have is a list of lists - so there is no concept of a column there. There are two ways to do this, one is (as Pavel Anossov's answer shows) is to use a list comprehension.

One is to use zip() which can be used to transpose an iterable:

>>> list(zip(*matrix))
[(0, 3, 9, 10), (1, 7, 4, 3)]

I've made it a list here to make it easier to show the output. Note in 2.x, zip() gives a list rather than an iterator (although a lazy version is available as itertools.izip()).

Generally, I would use zip() if you plan on working with more than one column, and the list comprehension if you only need one.

like image 124
Gareth Latty Avatar answered Oct 18 '25 08:10

Gareth Latty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!