Python,与.append()方法有问题

时间:2017-06-23 17:28:18

标签: python list

我正在使用anaconda Python 3笔记本。当我尝试将任何内容添加到列表中时,我的电脑会发疯。它变得缓慢,RAM达到95%,它不再工作了。但我注意到了一些问题,这个问题只发生在我使用for语句时。如果我使用切片括号,我没有这个问题,所以这将是这样的:

问题:

for element in anylist:
       anylist.append('whatever')

(到目前为止,我认为这个永远不会停止工作,它可能会导致一些小问题。我真的不知道)

没问题:

for element in anylist[:]:
      anylist.append('whatever')

另一个细节:所有这一切都是在我导入String模块和Os模块之前开始的。但现在每次我编写单个代码时都会发生这种情况。

Python是64位,因为它必须在我的情况下。 如果你能帮助我,我将不胜感激。

2 个答案:

答案 0 :(得分:3)

第一个例子可以翻译为:

while there is something more in anylist add whatever to the end

表示列表会一直增长,直到系统崩溃。

所以永远不会结束。第二个翻译为:

for the number of items in anylist add whatever to the end of the list.

因此会使列表的长度加倍。

因此,python正在完成您要告诉它的事情(我怀疑这不是您认为的那样)。

答案 1 :(得分:0)

尝试做:

for element in range(len(anylist)):
    anylist.append('something')
相关问题