简体   繁体   English

在Python中从数组中选择列

[英]Selecting a column from an array in Python

In trying to select the first (when counting from zero) column in a 2D 4x4 array, I wrote the following script: 在尝试选择2D 4x4数组中的第一列(从零开始计数)时,我编写了以下脚本:

import numpy
a4x4=[list(range(4*i,4*(i+1))) for i in list(range(4))]
print(a4x4)
print(a4x4[:,1])

The array seems to be alright: 该数组似乎还不错:

[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]

but instead of 但是代替

[1, 5, 9, 13] [1、5、9、13]

for the second print, I get this error: 对于第二次打印,我收到此错误:

TypeError: list indices must be integers, not tuple TypeError:列表索引必须是整数,而不是元组

Why does this error appear, what is going wrong? 为什么会出现此错误,这是怎么回事?

You've import numpy but you aren't using it. 您已导入numpy,但未使用它。 What you have instead is a list of lists, and Python doesn't support multidimensional slicing for that (ie, you'd need [a4x4[i][1] for i in range(4)] to get the result you expect, but really you should be using numpy). 相反,您只有一个列表列表,而Python不支持该方法的[a4x4[i][1] for i in range(4)]片(即,您需要[a4x4[i][1] for i in range(4)]来获得期望的结果,但实际上您应该使用numpy)。 Here's an example: 这是一个例子:

import numpy
a4x4=numpy.array([list(range(4*i,4*(i+1))) for i in list(range(4))])
print(a4x4)
print(a4x4[:,1])

By the way, in numpy you can also build the array you want directly, like this: 顺便说一下,在numpy中,您还可以直接构建所需的数组,如下所示:

 numpy.arange(4*4).reshape((4,4))

(And also in Python one doesn't need the list calls I have above, I'm just trying to keep the code as similar to yours as possible to see the key thing, which is converting the list of lists into a numpy array.) (而且在Python中,不需要上面的list调用,我只是想使代码尽可能与您的代码相似,以查看关键,即将列表列表转换为numpy数组。 )

You can produce the result you want using list comprehension - just as you created the original 4x4: 您可以使用列表推导来产生想要的结果-就像创建原始4x4一样:

a4x4=[list(range(4*i,4*(i+1))) for i in list(range(4))]
print([a4x4[i][1] for i in range(4)])

furthermore, you can simplify your logic a bit by tossing out the list function: 此外,您可以通过抛出list函数来简化逻辑:

a4x4 = [range(4*i,4*(i+1)) for i in range(4)]
print([a4x4[i][1] for i in range(4)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM