Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print column in python array?

I have an array of 3 numbers per row, 4 columns deep. I am struggling to figure out how I can write the code to print all numbers from a specified column rather than from a row.

I have searched for tutorials that explain this easily and just cannot find any that have helped. Can anyone point me in the right direction?

like image 423
ZombieDude Avatar asked Jan 08 '23 17:01

ZombieDude


2 Answers

If you're thinking of python lists as rows and columns, probably better to use numpy arrays (if you're not already). Then you can print the various rows and columns easily, E.g.

import numpy as np
a = np.array([[1,2,6],[4,5,8],[8,3,5],[6,5,4]])
#Print first column
print(a[:,0])
#Print second row
print(a[1,:])

Note that otherwise you have a list of lists and you'd need to use something like,

b = [[1,2,6],[4,5,8],[8,3,5],[6,5,4]]
print([i[0] for i in b])
like image 97
Ed Smith Avatar answered Jan 18 '23 12:01

Ed Smith


You can do this:

>>> a = [[1,2,3],[1,1,1],[2,1,1],[4,1,2]]
>>> print [row[0] for row in a]
[1, 1, 2, 4]
like image 35
Harold Ship Avatar answered Jan 18 '23 11:01

Harold Ship