元组切片 [英] Tuple slices

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

问题描述

为什么切片元组会返回一个新元组而不是现有元组的视图,因为

元组是不可变的?我最后编写了一个自定义的ImmutableSequence类来执行此操作,但是我想知道为什么它没有为元组实现。


George

解决方案

George Sakkis写道:

为什么切片元组会返回一个新的元组而不是现有元组的视图,给定
元组是不可变的吗?




真的吗?

a = 1,2,3
b = a [:]
a是b



True


< / F>


Fredrik Lundh写道:

George Sakkis写道:

为什么切片元组会返回一个新元组而不是现有元组的视图,因为
元组是不可变的?



真的吗?

a = 1,2,3
b = a [:]
a是b


True




我的印象是完整的元组副本实际上并没有复制,但是这可能是一个元组子集的切片。不完全确定如何测试这个,但是:


py> a = 1,2,3

py> a [:2]是[:2]

False


所以_something_至少在两个切片之间是不同的......


Steve


2005年1月24日星期一18:45:46 +0100

" Fredrik Lundh" < FR ***** @ pythonware.com>写道:

George Sakkis写道:

为什么切片元组会返回一个新的元组而不是现有的视图
一,鉴于元组是不可变的吗?
真的吗?




嗯......好像这个案例已经过优化,可以返回原来的元组

只是递增其引用计数并返回


tupleobject.c,330-335

if(ilow == 0&& ; ihigh == a-> ob_size&& PyTuple_CheckExact(a)){

Py_INCREF(a);

return(PyObject *)a;

}

a = 1,2,3
b = a [:]
a是b


真的

< / F>

-
http://mail.python.org/mailman/listinfo/python-list



Why does slicing a tuple returns a new tuple instead of a view of the existing one, given that
tuples are immutable ? I ended up writing a custom ImmutableSequence class that does this, but I
wonder why it is not implemented for tuples.

George

解决方案

George Sakkis wrote:

Why does slicing a tuple returns a new tuple instead of a view of the existing one, given that
tuples are immutable ?



really?

a = 1, 2, 3
b = a[:]
a is b


True

</F>


Fredrik Lundh wrote:

George Sakkis wrote:

Why does slicing a tuple returns a new tuple instead of a view of the existing one, given that
tuples are immutable ?



really?

a = 1, 2, 3
b = a[:]
a is b


True



My impression was that full tuple copies didn''t actually copy, but that
slicing a subset of a tuple might. Not exactly sure how to test this, but:

py> a = 1, 2, 3
py> a[:2] is a[:2]
False

So _something_ at least is different between the two slices...

Steve


On Mon, 24 Jan 2005 18:45:46 +0100
"Fredrik Lundh" <fr*****@pythonware.com> wrote:

George Sakkis wrote:

Why does slicing a tuple returns a new tuple instead of a view of
the existing one, given that tuples are immutable ?
really?



Well... seems like this case is optimized to return the original tuple
just incrementing its reference count and returning

tupleobject.c, 330-335

if (ilow == 0 && ihigh == a->ob_size && PyTuple_CheckExact(a)) {
Py_INCREF(a);
return (PyObject *)a;
}

a = 1, 2, 3
b = a[:]
a is b


True

</F>

--
http://mail.python.org/mailman/listinfo/python-list



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

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