扩展切片语法实际上对否定步骤有什么作用? [英] What does extended slice syntax actually do for negative steps?

查看:73
本文介绍了扩展切片语法实际上对否定步骤有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中的扩展片语法已向我解释为"a[n:m:k] returns every kth element from n to m".

The extended slice syntax in python has been explained to me as "a[n:m:k] returns every kth element from n to m".

这给我一个很好的主意,当k为正数时会发生什么.但是我对如何解释a[n:m:k]为负k迷失了.我知道a[::-1]反转a,并且a[::-k]接受反转a的第k个元素.

This gives me a good idea what to expect when k is positive. But I'm lost on how to interpret a[n:m:k] for negative k. I know that a[::-1] reverses a, and that a[::-k] takes ever kth element of the reversed a.

但是,这对k正数的定义如何泛化?我想知道a[n:m:k]的实际定义,以便(例如)我能理解为什么:

But how is this a generalization of the definition for k positive? I'd like to know how a[n:m:k] is actually defined, so that (for example) I can understand why:

"abcd"[-1:0:-1] = "dcb"

a[n:m:-k]是否颠倒了序列a,然后采用原始索引从n开始到m之前结束一个的元素?我不这么认为,因为这种模式不适合我尝试过的其他n和m值.但是我不知该如何定义它,而搜索却使我无所适从.

Is a[n:m:-k] reversing the sequence a, then taking the elements with original indices starting from n and ending one before m or something? I don't think so, because this pattern doesn't fit other values of n and m I've tried. But I'm at a loss to figure out how this is actually defined, and searching has gotten me nowhere.

推荐答案

[-1:0:-1]的意思是:从索引len(string)-1开始并向上移动到0(不包括),然后执行-1(反向).

[-1:0:-1] means: start from the index len(string)-1 and move up to 0(not included) and take a step of -1(reverse).

因此,将获取以下索引:

So, the following indexes are fetched:

le-1, le-1-1, le-1-1-1  .... 1  # le is len(string)

示例:

In [24]: strs = 'foobar'

In [25]: le = len(strs)

In [26]: strs[-1:0:-1]  # the first -1 is equivalent to len(strs)-1

Out[26]: 'raboo'

In [27]: strs[le-1:0:-1]   
Out[27]: 'raboo'

这篇关于扩展切片语法实际上对否定步骤有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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