python中列表切片语法的问题
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
a[start:stop,i]
调用方法a.__getitem__((slice(start,stop,None), i))
。如果
a
是列表,则会引发TypeError
,但如果a
是 numpy 数组,则它是有效且有用的表示法。事实上,我相信 Numpy 的开发者要求 Python 的开发者精确地扩展有效的 Python 切片表示法,以便 numpy 数组切片表示法可以更容易地实现。例如,
1:3
选择第 1 行和第 2 行,2
选择第三列:PS。要试验哪个切片被发送到
__getitem__
,您可以玩一下这个玩具代码:
a[start:stop,i]
calls the methoda.__getitem__((slice(start,stop,None), i))
.This raises a
TypeError
ifa
is a list, but it is valid and useful notation ifa
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,
1:3
selects rows 1 and 2, and the2
selects the third column:PS. To experiment with what slice is getting sent to
__getitem__
, you canplay around with this toy code:
符号
[:,:]
用于切片 多维数组。 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.