python中列表切片语法的问题

发布于 2024-08-31 01:03:17 字数 382 浏览 10 评论 0原文

python 的文档中提到了扩展索引语法。

slice([start], stop[, step])

使用扩展索引语法时也会生成切片对象。例如:a[start:stop:step]a[start:stop, i]。请参阅 itertools.islice() 了解返回迭代器的替代版本。

a[start:stop:step] 按描述工作。但第二个呢?它是如何使用的?

The extended indexing syntax is mentioned in python's doc.

slice([start], stop[, step])

Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.

a[start:stop:step] works as described. But what about the second one? How is it used?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

街角迷惘 2024-09-07 01:03:17

a[start:stop,i] 调用方法 a.__getitem__((slice(start,stop,None), i))

如果 a 是列表,则会引发 TypeError,但如果 a 是 numpy 数组,则它是有效且有用的表示法。事实上,我相信 Numpy 的开发者要求 Python 的开发者精确地扩展有效的 Python 切片表示法,以便 numpy 数组切片表示法可以更容易地实现。

例如,

import numpy as np
arr=np.arange(12).reshape(4,3)
print(arr)
# [[ 0  1  2]
#  [ 3  4  5]
#  [ 6  7  8]
#  [ 9 10 11]]

1:3 选择第 1 行和第 2 行,2 选择第三列:

print(arr[1:3,2])
# [5 8]

PS。要试验哪个切片被发送到 __getitem__,您可以
玩一下这个玩具代码:

class Foo(list):
    def __getitem__(self,key):
        return repr(key)

foo=Foo(range(10))
print(foo[1:5,1,2])
# (slice(1, 5, None), 1, 2)

a[start:stop,i] calls the method a.__getitem__((slice(start,stop,None), i)).

This raises a TypeError if a is a list, but it is valid and useful notation if a is a numpy array. In fact, I believe the developers of Numpy asked the developers of Python to extend valid Python slicing notation precisely so that numpy array slicing notation could be implemented more easily.

For example,

import numpy as np
arr=np.arange(12).reshape(4,3)
print(arr)
# [[ 0  1  2]
#  [ 3  4  5]
#  [ 6  7  8]
#  [ 9 10 11]]

1:3 selects rows 1 and 2, and the 2 selects the third column:

print(arr[1:3,2])
# [5 8]

PS. To experiment with what slice is getting sent to __getitem__, you can
play around with this toy code:

class Foo(list):
    def __getitem__(self,key):
        return repr(key)

foo=Foo(range(10))
print(foo[1:5,1,2])
# (slice(1, 5, None), 1, 2)
雾里花 2024-09-07 01:03:17

符号 [:,:] 用于切片 多维数组。 Python 默认情况下没有任何多维数组,但语法支持它,例如 numpy 利用这个语法。

The notation [:,:] is used to slice multidimensional arrays. Python doesn't have any multi-dimensional arrays by default, but the syntax supports it and numpy for example takes advantage of this syntax.

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