简体   繁体   English

元组切片在Python中到底如何工作?

[英]How exactly does tuple slicing work in Python?

For list slicing I could imagine (although I could be totally off...) the code being something along the lines of instantiating a list of size range_end - range_start and inputting values from the original list into the newly created array. 对于列表切片,我可以想象(尽管我可能完全不了解 ...)代码类似于实例化大小为range_end-range_start的列表并将原始列表中的值输入到新创建的数组中。

How exactly does tuple slicing work? 元组切片到底如何工作? It's not like we could potentially instantiate a tuple of size range_end - range_start and update the values since tuples are immutable. 因为元组是不可变的,所以我们不可能实例化一个大小为range_end-range_start的元组并更新值。

I've tried a couple of tests and it seems tuple slicing and list slicing perform similarly on average: 我尝试了几次测试,似乎元组切片和列表切片的平均表现相似:

import time

_max = 10000000
_list = range(_max)
_tuple = tuple(_list)

mid = _max // 2
i = 10000
while i <= _max:
    print 'for', i,  ' elements :'
    s = mid - half
    e = mid + half - 1
    # list slice
    start = time.clock()
    lSlice = _list[s:e]
    end = time.clock()
    print 'list slice took:',  end - start
    # tuple slice
    start = time.clock()
    tSlice = _tuple[s:e]
    end = time.clock()
    print 'tuple slice took:', end - start
    i *= 10

Which yielded: 产生了:

for 10000  elements :
list slice took: 6.78296778938e-05
tuple slice took: 2.94523601381e-05
for 100000  elements :
list slice took: 0.000377971955106
tuple slice took: 0.000270872463694
for 1000000  elements :
list slice took: 0.00472353381912
tuple slice took: 0.00548037022509
for 10000000  elements :
list slice took: 0.0499159492116
tuple slice took: 0.0504157468382

Could anyone give me some insight into how the tuple slicing routine works? 谁能给我一些有关元组切片例程工作原理的见解?

edit: I noticed my setup for start and end points of slices were ridiculous so I updated the code snippet. 编辑:我注意到我的切片起点和终点的设置是荒谬的,所以我更新了代码片段。

It's not like we could potentially instantiate a tuple of size range_end - range_start and update the values since tuples are immutable. 因为元组是不可变的,所以我们不可能实例化一个大小为range_end-range_start的元组并更新值。

You can't at Python level, but it's entirely possible in the underlying C implementation, and that's how it's done . 您不能处于Python级别,但是在底层C实现中完全有可能, 这就是完成的方式 That's how any tuple gets its values filled in, whether through slicing, the tuple constructor, (a, b, c) syntax, or anything else. 这就是任何元组如何通过切片, tuple构造函数, (a, b, c)语法或其他任何方式填充其值的方式。

else if (PySlice_Check(item)) {
    ...
        result = PyTuple_New(slicelength);
        if (!result) return NULL;

        src = self->ob_item;
        dest = ((PyTupleObject *)result)->ob_item;
        for (cur = start, i = 0; i < slicelength;
             cur += step, i++) {
            it = src[cur];
            Py_INCREF(it);
            dest[i] = it;
        }

        return result;

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

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