从字典中的列表中删除元素,Python

Deleting elements from lists in a dictionary, Python

我有一本字典,其中包含某些键和情侣列表作为元素。 我想执行以下操作:从其第二个元素(或第一个,并不重要)满足特定条件的所有列表中删除每个元素(对)。 我尝试用一​​段非常简单的代码来做到这一点,但我没有成功,事实上我注意到了一个特定的行为:从列表中删除一个元素让列表的元素 for 循环跳过以下元素,出于某种原因(或在至少在我看来是这样的)。

这是一个非常简单的例子:

# random dictionary
a = {'a': [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [1, 7]],
     'b': [[2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7]]}

def f(d):
    
    # keys in the dicitonary
    for key in list(d):
        
        # elements inthe list
        for elem in d[key]:
            
            # if the second element of the couple
            # satisfies a certain criterion...
            if elem[1] >= 2:
                
                # remove that element (first occurrence) from the list
                d[key].remove(elem)
        
    return d

b = f(a)
print(b)

这是我得到的输出:

{'a': [[1, 1], [1, 3], [1, 5], [1, 7]], 'b': [[2, 1], [2, 3], [2, 5], [2, 7]]}

这是我想要的:

{'a': [[1, 1]], 'b': [[2, 1]]}

如何正确执行上述操作?

编辑:我知道有一些解决方法。 我现在的问题是关于 for 循环中发生的跳过事件:为什么会发生?为什么代码不能像我认为的那样工作?

您可以遍历值(列表)并在嵌套循环中再次遍历这些列表,如果某个值不满足您的条件,则忽略它。

# random dictionary
a = {'a': [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [1, 7]],
     'b': [[2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7]]}

def f(d):
    # iterate over the keys
    for key in d.keys():
        value_list = d[key]
        # create a temporary list
        temp_list = []
        for elem in value_list:
            # if some element doesn't match the criteria, skip it
            if elem[1] >= 2:
                continue
            # if the condition is satisfied, add it to the temporary list
            temp_list.append(elem)
        # replace the key's value with the modified list
        d[key] = temp_list
    
    return d

b = f(a)
print(b)

当您删除列表元素时,所有索引都会进行调整以反映删除。如果你从列表的末尾开始工作,你将不会遇到你看到的跳过,例如

'mylist = [1,23,3,4,5,6,7,8,9]
     r = range(len(mylist)-1,0,-1)
     for i in r:
        if mylist[i] % 2 :
            mylist.pop(i)

'