【问题标题】:Removing while iterating on sequences in python在python中迭代序列时删除
【发布时间】:2014-03-15 13:28:14
【问题描述】:

谁能解释一下removing items from a list 是如何工作的以及为什么removing items from a set 不工作?

虽然我们可以迭代列表和集合,但为什么不能对集合进行更改?是不是因为集合没有排序?

【问题讨论】:

  • 先阅读文档

标签: python list python-2.7 set


【解决方案1】:

在底层 SET 实现与 LIST 完全不同。

列表: Python 的列表是可变长度数组,而不是 Lisp 样式的链表。该实现使用对其他对象的连续引用数组,并将指向该数组的指针和数组的长度保存在列表头结构中。

集合:集合使用哈希表作为其底层数据结构。就像字典一样,但具有虚拟值。我们将键用作列表中的元素。

Dictionaries or Set 实现一个 tp_iter 槽,该槽返回一个高效的迭代器,该迭代器对字典的键进行迭代。在这样的迭代期间,dictionary 或 set 不应被修改,除非为现有键设置值 允许(不允许删除或添加,update() 方法也不允许)。这意味着我们可以写

所以,当你迭代一个集合时

>>> for i in s:
...     s.pop()
...
0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: Set changed size during iteration
>>>

但如果你使用while,你可以删除或更新它:

>>> s = set(range(5))
>>> while s:
...     s.pop()
...     print s
...
0
set([1, 2, 3, 4])
1
set([2, 3, 4])
2
set([3, 4])
3
set([4])
4
set([])
>>>

You can see here in the source code:

【讨论】:

    猜你喜欢
    • 2021-03-04
    • 2012-11-11
    • 2017-09-17
    • 2011-09-23
    • 2011-11-26
    • 2011-03-18
    • 2011-02-25
    • 2011-01-27
    相关资源
    最近更新 更多