如何在python数组中打印列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29156187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:09:36  来源:igfitidea点击:

How to print column in python array?

pythonpython-3.x

提问by ZombieDude

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.

我有一个每行 3 个数字、4 列深的数组。我正在努力弄清楚如何编写代码来打印指定列而不是行中的所有数字。

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?

我已经搜索了可以轻松解释这一点的教程,但找不到任何有帮助的教程。任何人都可以指出我正确的方向吗?

采纳答案by Ed Smith

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.

如果您将 python 列表视为行和列,最好使用 numpy 数组(如果您还没有)。然后您可以轻松打印各种行和列,例如

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])

回答by Harold Ship

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]