[英]For-loop with range is only taking the last element
I have a 2D array of strings from which I delete certain elements (those containing the '#' char). 我有一个二维字符串数组,从中删除某些元素(那些包含'#'char的元素)。 When I print
lista
from inside the loop, it prints this: 当我从循环内部打印
lista
,它会打印以下内容:
['call', '_imprimirArray']
['movl', '24', '%2', '%3']
['movl', '%1', '%2']
['call', '_buscarMayor']
['movl', '%1', '4', '%3']
['movl', '$LC1', '%2']
['call', '_printf']
['movl', '$LC2', '%2']
['call', '_system']
['movl', '$0', '%2']
['movl', '-4', '%2', '%3']
But when I append each row to another 2D array, only the last element is assigned: 但是,当我将每一行附加到另一个2D数组时,只会分配最后一个元素:
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3']
Here's the loop: 这是循环:
def quitarEtiquetas(labels, programa):
lista = []
temp = []
for i in range(0, len(programa)):
del lista[:]
for j in range(0, len(programa[i])):
if(programa[i][j].find('#') != -1):
labels.append([programa[i][j].replace('#', ''), i])
else:
lista.append(programa[i][j])
print(lista)
temp.append(lista)
You're appending the same row many times to temp
while just removing items from it on each iteration. 您要向
temp
多次添加同一行,而每次迭代都只是从该行中删除项目。 Instead of del lista[:]
just assign a new list to the variable: lista = []
so that content in previously added rows doesn't get overwritten. 代替
del lista[:]
而是给变量分配一个新列表: lista = []
这样先前添加的行中的内容就不会被覆盖。
Effectively you're doing following: 实际上,您正在执行以下操作:
>>> lista = []
>>> temp = []
>>> lista.append('foo')
>>> temp.append(lista)
>>> temp
[['foo']]
>>> del lista[:]
>>> temp
[[]]
>>> lista.append('bar')
>>> temp.append(lista)
>>> temp
[['bar'], ['bar']]
Adding to niemmi's answer, what you need to do is: 除了涅米的答案,您需要做的是:
for i in range(0, len(programa)):
lista = [] # creates a new empty list object alltogether
...
instead of 代替
for i in range(0, len(programa)):
del lista[:]; # only clears the content, the list object stays the same
BTW, no ;
顺便说一句,没有
;
needed in python. 在python中需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.