迭代时从列表中删除 [英] Delete from a list while iterating

查看:66
本文介绍了迭代时从列表中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单

a = [1,2,3,4,5,6,7,8,9]

b = [10,11,12,13,14,15,16,17,18]

遍历列表b时,如果任何数字小于15,则从列表a中删除其对应的数字(索引).

While traversing list b , if any number is less than 15, then remove its corresponding number (index) from list a.

例如:-列表b 10,11,12,13,14中的值小于15,因此应删除列表a中的对应项,即1,2,3,4,5.

For eg:- in list b 10,11,12,13,14 are less than 15, hence its counterpart from list a should be removed, ie 1,2,3,4,5.

目前,这是我的工作方式:

Currently, this is how I'm doing:

for index, i in enumerate(b):
    if i < 15:
        del(a[index])

这返回了超出范围的索引错误.

This returns me an out of range index error.

我该怎么做?

推荐答案

您应该使用列表理解和zip,而不是从a中删除元素,而应使用b值超过15的元素.示例-

You should use list comprehension and zip and instead of deleting elements from a , instead take elements in a whose b value is over 15. Example -

a[:] = [i for i,j in zip(a,b) if j >=15]

我们在左侧使用了a[:],所以a列表对象就地发生了突变. (这与a = <something>不同,后者只是将名称a绑定到新列表,而前者将列表原地更改).

We are using a[:] on the left side, so that a list object gets mutated inplace. (This is different from a = <something> as the latter simply binds name a to a new list whereas former mutates the list inplace).

演示-

>>> a = [1,2,3,4,5,6,7,8,9]
>>>
>>> b = [10,11,12,13,14,15,16,17,18]
>>> a[:] = [i for i,j in zip(a,b) if j >=15]
>>> a
[6, 7, 8, 9]

这篇关于迭代时从列表中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆