问题描述
我是 Python 和 numpy 的新手.我已经想出了如何对一维序列进行切片:arr[start:end]
,并访问数组中的一个元素:el = arr[row][col]
.
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]
.
尝试像 slice = arr[0:2][0:2]
(其中 arr
是一个 numpy 数组)之类的东西不会给我前 2 行和列,但重复前 2 行.我刚刚做了什么,如何沿着另一个维度切片?
Trying something like slice = arr[0:2][0:2]
(where arr
is 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?
推荐答案
如果你使用 numpy
,这很容易:
If you use numpy
, this is easy:
slice = arr[:2,:2]
或者如果你想要 0,
slice = arr[0:2,0:2]
你会得到同样的结果.
*注意 slice
实际上是内置类型的名称.一般来说,我会建议给你的对象一个不同的名称".
*note that slice
is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".
另一种方式,如果您正在处理列表列表*:
Another way, if you're working with lists of lists*:
slice = [arr[i][0:2] for i in range(0,2)]
(注意这里的 0 是不必要的:[arr[i][:2] for i in range(2)]
也可以.).
(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)]
would also work.).
我在这里所做的是一次获取每个所需的第 1 行 (arr[i]
).然后我从该行中切出我想要的列并将其添加到我正在构建的列表中.
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.
如果你天真地尝试:arr[0:2]
你会得到前 2 行,如果你再次切片 arr[0:2][0:2]
,你只是再次切片前两行.
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.
*这实际上也适用于 numpy 数组,但与我上面发布的本机"解决方案相比它会很慢.
*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.
这篇关于Python:切片多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!