Python:切片多维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17277100/
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 00:56:04  来源:igfitidea点击:

Python: slicing a multi-dimensional array

pythonarraysnumpy

提问by SlightlyCuban

I'm new to Python and numpy. I've figured out how to slice 1 dimensional sequence: arr[start:end], and access an element in the array: el = arr[row][col].

我是 Python 和 numpy 的新手。我已经想出了如何对一维序列进行切片:arr[start:end],并访问数组中的元素:el = arr[row][col]

Trying something like slice = arr[0:2][0:2](where arris a numpy array) doesn't give me the first 2 rows and columns, but repeats the first 2 rows. What did I just do, and how do I slice along another dimension?

尝试类似slice = arr[0:2][0:2](where arris a numpy array) 不会给我前 2 行和列,而是重复前 2 行。我刚刚做了什么,我如何沿着另一个维度切片?

采纳答案by mgilson

If you use numpy, this is easy:

如果您使用numpy,这很容易:

slice = arr[:2,:2]

or if you want the 0's,

或者如果你想要0,

slice = arr[0:2,0:2]

You'll get the same result.

你会得到同样的结果。

*note that sliceis actually the name of a builtin-type. Generally, I would advise giving your object a different "name".

*请注意,这slice实际上是内置类型的名称。一般来说,我会建议给你的对象一个不同的“名称”。



Another way, if you're working with lists of lists*:

另一种方式,如果您正在使用列表列表*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)]would also work.).

(请注意,这里的 0 是不必要的: [arr[i][:2] for i in range(2)]也可以。)。

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

我在这里所做的是一次获取每个所需的第 1 行 ( arr[i])。然后我从该行中切出我想要的列并将其添加到我正在构建的列表中。

If you naively try: arr[0:2]You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

如果你天真地尝试:arr[0:2]你得到前两行,如果你再次切片arr[0:2][0:2],你只是再次切片前两行。

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

*这实际上也适用于 numpy 数组,但与我上面发布的“本机”解决方案相比,它会很慢。