对整个列表进行切片的切片分配与直接分配之间有什么区别

对整个列表进行切片的切片分配与直接分配之间有什么区别

本文介绍了对整个列表进行切片的切片分配与直接分配之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在很多地方看到list使用切片分配.当与(非默认)索引一起使用时,我能够理解它的用法,但是我无法理解它的用法,如:

I see at many places the use of slice assignment for lists. I am able to understand its use when used with (non-default) indices, but I am not able to understand its use like:

a_list[:] = ['foo', 'bar']

a_list = ['foo', 'bar']

?

推荐答案

a_list = ['foo', 'bar']

在内存中创建一个新的list,并在其上指向名称a_list. a_list之前指出的内容无关紧要.

Creates a new list in memory and points the name a_list at it. It is irrelevant what a_list pointed at before.

a_list[:] = ['foo', 'bar']

用a_list对象的 __setitem__ 方法="http://docs.python.org/library/functions.html#slice"> slice 作为索引,并在内存中创建一个新的list作为该值.

Calls the __setitem__ method of the a_list object with a slice as the index, and a new list created in memory as the value.

__setitem__slice求值以找出其代表的索引,并在其传递的值上调用iter.然后,它遍历对象,将在slice指定的范围内的每个索引设置为该对象的下一个值.对于list,如果slice指定的范围与可迭代对象的长度不同,则将调整list的大小.这使您可以做很多有趣的事情,例如删除列表的各个部分:

__setitem__ evaluates the slice to figure out what indexes it represents, and calls iter on the value it was passed. It then iterates over the object, setting each index within the range specified by the slice to the next value from the object. For lists, if the range specified by the slice is not the same length as the iterable, the list is resized. This allows you to do a number of interesting things, like delete sections of a list:

a_list[:] = [] # deletes all the items in the list, equivalent to 'del a_list[:]'

或在列表中间插入新值:

or inserting new values in the middle of a list:

a_list[1:1] = [1, 2, 3] # inserts the new values at index 1 in the list

但是,对于step不是一个的扩展切片",可迭代的长度必须正确:

However, with "extended slices", where the step is not one, the iterable must be the correct length:

>>> lst = [1, 2, 3]
>>> lst[::2] = []
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
ValueError: attempt to assign sequence of size 0 to extended slice of size 2

将切片分配给a_list的主要不同之处是:

The main things that are different about slice assignment to a_list are:

  1. a_list必须已经指向一个对象
  2. 该对象已修改,而不是将a_list指向新对象
  3. 该对象必须支持具有slice索引的__setitem__
  4. 右侧的对象必须支持迭代
  5. 没有名称指向右边的对象.如果没有其他引用(例如,如您的示例中的文字所示),则在迭代完成后,该引用将被计数为不存在.
  1. a_list must already point to an object
  2. That object is modified, instead of pointing a_list at a new object
  3. That object must support __setitem__ with a slice index
  4. The object on the right must support iteration
  5. No name is pointed at the object on the right. If there are no other references to it (such as when it is a literal as in your example), it will be reference counted out of existence after the iteration is complete.

这篇关于对整个列表进行切片的切片分配与直接分配之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 17:55