问题:
test1 = [1, 2, 3]
for i in range(len(test1)): #Want to do the below for every element in test1
print(test1[i])
if test1[i] % 2 == 0: #if the element meets certain conditions, it gets deleted
del test1[i]
#The thing in test1 gets deleted, but the range gets not updated,
#and i iterates nonetheless, so 1 element gets ignored,
#and in the end, I get "list index out of range"
(在实际代码中,if 语句要多得多,而且数组中的东西不是整数而是对象?!一个类的,所以列表理解更多-嗯...)
我想出了这个方法:
test1 = [1, 2, 3]
i = 0
x = len(test1)
while i < x:
print(test1[i])
if test1[i] % 2 == 0:
del test1[i]
x -= 1
i -= 1
i += 1
但是如您所见,这多了 5 行(并且对于每个 del,我必须添加 2 行...),丑陋且烦人。有没有更好的方法来做这样的事情?比如,直接进入 for 循环、更新范围并让您选择 i 或其他内容的重做命令?
最佳答案
使用列表理解
类似的东西:
list = [x for x in list if x % 2 == 1] # Keep anything that is not even
for thing in list:
print(thing)
这将创建一个包含与条件匹配的任何内容的新列表。 然后打印新列表
>>> test1 = [1,2,3]
>>> list = [x for x in test1 if x % 2 is 1]
>>> print(list)
[1, 3]
关于Python:循环中的del,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29477706/