切片表示嵌套列表的 NumPy 数组
我熟悉切片,我只是无法理解这一点,并且我尝试更改一些值来尝试说明正在发生的事情,但这对我来说没有意义。
这是示例:
import numpy
l = numpy.array([[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 1]])
print(l[:,0:2].tolist())
结果:
[[0, 0], [0, 1], [1, 0], [1, 1]]
我试图将其翻译为“从索引 0
到 0,2
的切片,递增 2
”这对我来说毫无意义。
I'm familiar with slicing, I just can't wrap my head around this, and I've tried changing some of the values to try and illustrate what's going on, but it makes no sense to me.
Here's the example:
import numpy
l = numpy.array([[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 1]])
print(l[:,0:2].tolist())
Resulting in:
[[0, 0], [0, 1], [1, 0], [1, 1]]
I'm trying to translate this as "slice from index 0
to 0,2
, incrementing by 2
" which makes no sense to me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在做的是多轴切片。因为
l
是一个二维数组,并且您希望对第二个维度进行切片,所以您使用逗号来指示下一个维度。, 0:2
选择第二个维度的前两个元素。这里有一个非常好的解释。我记得当我第一次了解它时,它很好地澄清了事情。
What you are doing is multi-axis slicing. Because
l
is a two dimensional array and you wish to slice the second dimension you use a comma to indicate the next dimension.the
, 0:2
selects the first two elements of the second dimension.There's a really nice explanation here. I remember it clarifying things well when I first learned about it.
以下应该适用于普通列表。假设它是一个列表的列表,
并且所有子列表的长度都相同,那么你可以这样做(python 2)
输出将是:
The following should work for ordinary lists. Assuming that it is a list of lists,
and all the sublists are of the same length, then you can do this (python 2)
Output will be: