了解列表切片中的负面步骤 [英] Understanding negative steps in list slicing

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

问题描述

我试图理解以下行为,欢迎您提供任何参考(尤其是官方文档)或评论.

I am trying to understand the following behavior and would welcome any references (especially to official docs) or comments.

让我们考虑一个列表:

>>> x = [1,2,3,4,5,6]

这按预期工作

>>> x[-1:-4:-1] 
[6, 5, 4]

但我很惊讶以下内容为空:

But I am surprised the following is empty:

>>>  x[0:-4:-1] 
[]

因此,我很惊讶以下内容不为空

Consequently, I am surprised the following is not empty

>>> x[0:-len(x)-1:-1]
> [1]

特别是

>>> x[0:-len(x):-1] 
[]

还有那个

>>> x[0:-len(x)-1] 
[]

为空.

推荐答案

我被指向参考实现(匿名受益人的帽子提示),发现从那里了解行为是相当简单的.完整地说,恕我直言,这种行为是不直观的,但是它定义得很好,并且与参考实现相匹配.

I was pointed to the reference implementation (hattip to the Anonymous Benefactor) and found that it is fairly straightforward to understand the behavior from there. To be complete, IMHO this behavior is unintuitive, but it nevertheless is well defined and matches the reference implementation.

两个 CPython 文件是相关的,即描述 list_subscript PySlice_AdjustIndices .在这种情况下,从列表中检索切片时,将调用 list_subscript .它会调用 PySlice_GetIndicesEx ,依次调用 PySlice_AdjustIndices .现在, PySlice_AdjustIndices 包含简单的if/then语句,用于调整索引.最后,它返回切片的长度.就我们而言,线条

Two CPython files are relevant, namely the ones describing list_subscript and PySlice_AdjustIndices. When retrieving a slice from a list as in this case, list_subscript is called. It calls PySlice_GetIndicesEx, which in turn calls PySlice_AdjustIndices. Now PySlice_AdjustIndices contains simple if/then statements, which adjust the indices. In the end it returns the length of the slice. To our case, the lines

if (*stop < 0) {
    *stop += length;
    if (*stop < 0) {
        *stop = (step < 0) ? -1 : 0;
    }
}

特别重要.调整后, x [0:-len(x)-1:-1] 变为 x [0:-1:-1] 并返回长度1.但是,当传递 x [0:-1:-1] 进行调整时,它变为长度的 x [0:len(x)-1:-1] 0.换句话说,在这种情况下 f(x)!= f(f(x)).

are of particular relevance. After the adjustment, x[0:-len(x)-1:-1] becomes x[0:-1:-1] and the length 1 is returned. However, when x[0:-1:-1] is passed to adjust, it becomes x[0:len(x)-1:-1] of length 0. In other words, f(x) != f(f(x)) in this case.

有趣的是, PySlice_AdjustIndices 中有以下注释:

It is amusing to note that there is the following comment in PySlice_AdjustIndices:

/* this is harder to get right than you might think */

最后,请注意,在python 文档.

Finally, note that the handing of the situation in question is not described in the python docs.

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

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