在迭代列表时,Python不会从列表中删除所有项目 [英] Python doesn't remove all the items from a list while iterating over the list

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

问题描述

我有一个字典和下面的列表

I have a dictionary and a list as given below

correction =  {u'drug.ind': u'Necrosis', "date": "exp"}
drugs =  [[u'drug.aus', u'Necrosis'], [u'drug.nz', u'Necrosis'], [u'drug.uk', u'Necrosis'], [u'drug.ind', u'Necrosis'], [u'cheapest', u'drug.ind'], [u'date', u'']]

现在基本上我会查看校正字典值,只要它与drugs列表中列表的第二个元素匹配,就将其删除.

Now basically I look at the correction dictionary value and whenever it matches for every second element of the lists in drugs list, I remove them.

这就是我要做的

if correction and drugs:
    for i,x in correction.items():
        for j,k in enumerate(drugs):
            if len(i.split(".")) > 1:  # need to do the operation only for drugs which is always given in this format
                if x == k[1]:
                    drugs.pop(j)

理想情况下,drugs列表现在应该看起来像

Ideally the drugs list should now look like

drugs = [['cheapest', 'drug.ind'], ['date', '']]

但是由于某种原因,它看起来像

But for some reason it looks like

[['drug.nz', 'Necrosis'], ['drug.ind', 'Necrosis'], ['cheapest', 'drug.ind'], ['date', '']]

我希望所有看起来像坏死的东西都将被删除.但是,它也可以将其删除.

I was hoping that everything that looks like Necrosis will be removed. But it removes it alternatively.

为什么我会遇到这种行为?我在做什么错了?

Why do I encounter this behaviour? What am I doing wrong?

推荐答案

因为当您从数组中弹出一个项目时,它会将列表中下一个项目的索引更改为位于迭代器之后".

Because when you pop an item from the array, it changes the index of the next item in the list to be 'behind' the iterator.

在下面的示例中,您看到我们实际上只对数组中的所有其他项运行print(),即使表面上我们迭代数组删除所有成员,但最终只删除了一半

In the below example you see that we only ever actually run print() for every other item in the array, even though on the face of it we're iterating through the array deleting all members, we end up only deleting half

example = ['apple','banana','carrot','donut','edam','fromage','ghee','honey']

for index,food in enumerate(example):
    print(food);
    example.pop(index)

print(example) 

这是因为for循环(基本上)在每个循环上递增整数i并在从example弹出元素时获取example[i],这会更改后面元素的位置,因此example[i]变化.

This is because what a for loop is (basically) doing is incrementing an integer i on each loop and getting example[i] as you pop elements from example it changes the position of the later elements so example[i] changes.

此代码演示了这一事实,正如您在弹出"一个元素后所看到的那样,下一个元素在我们眼前发生了变化.

This code demonstrates this fact, as you see after we 'pop' an element, the next element changes in front of our eyes.

example = ['apple','banana','carrot','donut','edam','fromage','ghee','honey']


for i in range(0,len(example)-1):
    print("The value of example[",i,"] is: ",example[i+1])
    example.pop(i)
    print("after popping ,the value of example[",i,"] is: ",example[i+1])

print(example)

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

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