我正在使用 Python 版本 3.2.3 的 Linux 机器上工作。
每当我尝试执行 list.clear()
时,我都会遇到异常
>>> l = [1, 2, 3, 4, 5, 6, 7]
>>> l.clear()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'clear'
同时在装有 Python 3.4.3 的 Mac 上,相同的代码运行流畅。 可能是由于 Python 版本之间的差异还是我遗漏了什么?
最佳答案
list.clear
是在 Python 3.3 中添加的。
引用 Mutable Sequence Types文档中的部分:
New in version 3.3:
clear()
andcopy()
methods.
s.clear()
removes all items froms
(same asdel s[:]
)
参见 issue #10516用于相关讨论和清算列表的替代方法。综上所述,与del l[:]
和l[:] = []
是一样的。
关于Python3 属性错误 : 'list' object has no attribute 'clear' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32055768/