python中列表切片语法的问题 [英] Problem with list slice syntax in python

查看:34
本文介绍了python中列表切片语法的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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] 按描述工作.但是第二个呢?怎么用?

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

推荐答案

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

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

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.

例如,

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 选择第三列:

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

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

附注.要试验发送到 __getitem__ 的切片,您可以玩这个玩具代码:

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)

这篇关于python中列表切片语法的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆