如何用负步读取切片 [英] How to read slicing with negative step

查看:56
本文介绍了如何用负步读取切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了一些有关切片的问题,但是还没有看到有关其中一些问题的有用答案,对此我很难理解. 假设我们有此列表a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 然后按以下方式对其进行切片:

I have already seen some questions about slicing, but haven't seen a helpful answer concerning some of them, which I can't manage to understand very well. Let's say we have this list a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] And I slice it in the following way:

a[:8:-1] #Ouput: [9]

为什么?我们给它一个8的结尾,一个-1的步长.它如何以这种方式表现?

Why? We give it an end of 8, and a step of -1. How come it behaves in this way?

推荐答案

如果省略slice表达式的第一部分,则默认为None.当需要使用list.__getitem__解释slice(None, 8, -1)的含义时,它将使用步长的符号来确定您是从0开始计数还是从列表末尾开始计数.在这种情况下,您要递减计数,因此:8:-1等效于slice(-1, 8, -1).

If you omit the first part of the slice expression, it defaults to None. When it comes time for list.__getitem__ to interpret what slice(None, 8, -1) means, it uses the sign of the step size to determine if you are counting up from 0 or down from the end of the list. In this case, you are counting down, so :8:-1 is equivalent to slice(-1, 8, -1).

这篇关于如何用负步读取切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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