Python:循环中的del

标签 python

问题:

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/

相关文章:

python - 如何随机更改numpy数组中某些元素的符号?

python - 电子邮件的正则表达式也适用于十进制值。我如何解决它?

python - 如何使用Python和Matlab的系统函数处理 'no module named library_name'错误?

python - 如何获取 python selenium 中的所有数据?

python - 奇怪的错误 : AssertionError: Request global variable is not set

python - django/休息 : Can I have serializer with only one field?

python - 如何为 jupyterhub 配置启动脚本?

Python 嵌套列表的内置求和

python - 删除 <select> 元素的正则表达式

python - 为什么列为键字典,仍然会显示为元组作为键字典