简体   繁体   English

以x [0:4:-1]的形式将元组切出索引

[英]slicing tuple out of index in a form of x[0:4:-1]

x = (1, 2, 3, 4)

Here, x[0:4:-1] gives an empty tuple () . 在这里, x[0:4:-1]给出一个空的tuple () Why is this happening? 为什么会这样呢? I thought it would just give a reversed tuple (4,3,2,1) ... 我认为(4,3,2,1)会给一个反向元组(4,3,2,1) ...

You're asking for all of the values starting at 0, ending before 4, counting by -1 at a time. 您需要所有从0开始,在4之前结束的值,一次以-1计数。 That's no values. 那没有价值。

What you want to do is start at 3, end before -1, counting by -1 at a time. 您想要做的是从3开始,在-1之前结束,一次以-1计数。 Except… you can't put -1 in there, because that means "1 from the end". 除了…您不能在其中放入-1 ,因为那意味着“从末尾开始1”。 So, you have to write "start at 3, end when you've exhausted the whole sequence, counting by -1 at a time", like this: 因此,您必须编写“从3开始,在用尽整个序列时结束,一次以-1计数”,如下所示:

x[3::-1]

Or, more simply: 或者,更简单地说:

x[::-1]

It may help your understanding to turn the slice into an explicit loop. 将切片变成显式循环可能会有助于您的理解。 It looks something like this: 看起来像这样:

def slicify(sequence, start, end, step):
    if start < 0: start += len(sequence)
    if end < 0: end += len(sequence)
    result = []
    while (start < end if step > 0 else start > end):
        result.append(sequence[start])
        start += step
    return result

But this is only roughly correct. 但这仅是大致正确的。 The exact definition is in the documentation under Sequence Types , under note 5: 确切的定义在文档中“ 序列类型 ”下的注释5中:

The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (ji)/k . 的切片sij与步骤k被定义为与索引项的序列x = i + n*k ,使得0 <= n < (ji)/k In other words, the indices are i , i+k , i+2*k , i+3*k and so on, stopping when j is reached (but never including j ). 换句话说,索引是ii+ki+2*ki+3*k等,当达到j时停止(但不包括j )。 If i or j is greater than len(s) , use len(s) . 如果ij大于len(s) ,请使用len(s) If i or j are omitted or None , they become “end” values (which end depends on the sign of k ). 如果省略ijNone ,它们将成为“结束”值(该结束取决于k的符号)。 Note, k cannot be zero. 注意, k不能为零。 If k is None , it is treated like 1 . 如果kNone ,则将其视为1

You'd need to either omit the start and end, or reverse the start and end: 您需要省略起点和终点,或者颠倒起点和终点:

x[::-1]    # (4, 3, 2, 1)
x[3:0:-1]  # (4, 3, 2)
x[3::-1]   # (4, 3, 2, 1)
x[3:-5:-1] # (4, 3, 2, 1)

The end point is not included, so slicing with [3:0:-1] only returns three elements. 端点不包括在内,因此使用[3:0:-1]切片只会返回三个元素。 The last example uses a negative value to be subtracted from the length of the tuple to end up with endpoint -1 . 最后一个示例使用一个负值从元组的长度中减去,以终结点-1结束。

Using a negative stride means Python wants to count backwards, and starting at 0 you'll never get to 4. 使用负的步幅表示Python希望倒数,从0开始,您永远不会达到4。

Note that the Python slice syntax applies to more than just tuples; 请注意,Python slice语法不仅适用于元组,还适用于其他语法。 strings and lists support the exact same syntax. 字符串和列表支持完全相同的语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM