切片表示嵌套列表的 NumPy 数组

发布于 2024-10-23 20:07:39 字数 352 浏览 5 评论 0原文

我熟悉切片,我只是无法理解这一点,并且我尝试更改一些值来尝试说明正在发生的事情,但这对我来说没有意义。

这是示例:

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

我试图将其翻译为“从索引 00,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

恏ㄋ傷疤忘ㄋ疼 2024-10-30 20:07:39

您正在做的是多轴切片。因为 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.

ㄖ落Θ余辉 2024-10-30 20:07:39

以下应该适用于普通列表。假设它是一个列表的列表,
并且所有子列表的长度都相同,那么你可以这样做(python 2)

A = [[1, 2], [3, 4], [5, 6]]
print (f"A = {A}")

flatA = sum(A, [])     # Flattens the 2D list
print (f"flatA = {flatA}")
len0 = len(A[0])
lenall = len(flatA)
B = [flatA[i:lenall:len0] for i in range(len0)] 
print (f"B = {B}")

输出将是:

A = [[1, 2], [3, 4], [5, 6]]
flatA = [1, 2, 3, 4, 5, 6]
B = [[1, 3, 5], [2, 4, 6]]

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)

A = [[1, 2], [3, 4], [5, 6]]
print (f"A = {A}")

flatA = sum(A, [])     # Flattens the 2D list
print (f"flatA = {flatA}")
len0 = len(A[0])
lenall = len(flatA)
B = [flatA[i:lenall:len0] for i in range(len0)] 
print (f"B = {B}")

Output will be:

A = [[1, 2], [3, 4], [5, 6]]
flatA = [1, 2, 3, 4, 5, 6]
B = [[1, 3, 5], [2, 4, 6]]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文