Python 是否对字符串进行逐个引用? [英] Does Python do slice-by-reference on strings?
问题描述
我想知道当我做类似的事情
a = "这可能是一个非常大的字符串..."b = a[:10]
创建一个新字符串或返回一个视图/迭代器
Python 做切片-by-copy,意思是每次你切片(除了 非常琐碎的切片,例如 a[:]
),它将所有数据复制到一个新的字符串对象中.
根据其中一位开发人员的说法,做出这个选择是因为
<块引用>[slice-by-reference] 方法更复杂,更难实现并可能导致意外行为.
例如:
<前>a = "一个有 500,000 个字符的长字符串......"b = a[0]德尔阿使用切片即复制设计,字符串 a
立即被释放.这切片作为参考设计会将 500kB 的字符串保留在内存中,尽管你只对第一个字符感兴趣.
显然,如果您绝对需要一个字符串视图,您可以使用 memoryview
对象.
I want to know if when I do something like
a = "This could be a very large string..."
b = a[:10]
a new string is created or a view/iterator is returned
Python does slice-by-copy, meaning every time you slice (except for very trivial slices, such as a[:]
), it copies all of the data into a new string object.
According to one of the developers, this choice was made because
The [slice-by-reference] approach is more complicated, harder to implement and may lead to unexpected behavior.
For example:
a = "a long string with 500,000 chars ..." b = a[0] del aWith the slice-as-copy design the string
a
is immediately freed. The slice-as-reference design would keep the 500kB string in memory although you are only interested in the first character.
Apparently, if you absolutely need a view into a string, you can use a memoryview
object.
这篇关于Python 是否对字符串进行逐个引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!