列表分配为[:] [英] List assignment with [:]

查看:73
本文介绍了列表分配为[:]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

list = range(100)

list[:] = range(100)

在Python中?

编辑

我应该提到,在该分配列表变量已分配给列表之前:

I should have mentioned that before that assignment list variable was already assigned to a list:

list = [1, 2, 3]
list = range(100)

list = [1, 2, 3]
list[:] = range(100)

推荐答案

执行时

lst = anything

您要将名称 lst指向一个对象.它不会改变所指向的旧对象lst ,尽管如果没有其他指向该对象的引用,其引用计数将下降为零,并且将被删除.

You're pointing the name lst at an object. It doesn't change the old object lst used to point to in any way, though if nothing else pointed to that object its reference count will drop to zero and it will get deleted.

这样做的时候

lst[:] = whatever

您要遍历whatever,创建一个中间元组,并将该元组的每个项目分配给已经存在的 lst对象中的索引.这意味着,如果多个名称指向同一对象,则引用任何名称时都会看到更改,就像使用appendextend或任何其他就地操作一样.

You're iterating over whatever, creating an intermediate tuple, and assigning each item of the tuple to an index in the already existing lst object. That means if multiple names point to the same object, you will see the change reflected when you reference any of the names, just as if you use append or extend or any of the other in-place operations.

差异示例:

>>> lst = range(1, 4)
>>> id(lst)
74339392
>>> lst = [1, 2, 3]
>>> id(lst)  # different; you pointed lst at a new object
73087936
>>> lst[:] = range(1, 4)
>>> id(lst)  # the same, you iterated over the list returned by range
73087936
>>> lst = xrange(1, 4)
>>> lst
xrange(1, 4)   # not a list, an xrange object
>>> id(lst)   # and different
73955976
>>> lst = [1, 2, 3]
>>> id(lst)    # again different
73105320
>>> lst[:] = xrange(1, 4) # this gets read temporarily into a tuple
>>> id(lst)   # the same, because you iterated over the xrange
73105320
>>> lst    # and still a list
[1, 2, 3]

在速度方面,切片分配速度较慢.有关其内存使用情况的更多信息,请参见 Python Slice分配内存使用情况.

When it comes to speed, slice assignment is slower. See Python Slice Assignment Memory Usage for more information about its memory usage.

这篇关于列表分配为[:]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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