首页 > 解决方案 > 如果 dict 键的值在 otherlist 中,则从列表中的 dicts 中删除元素

问题描述

我有如下代码:

dicts = [
        {'one': 'hello',
         'two': 'world',
         'three': ['a', 'b', 'c', 'd'],
         'four': 'foo'
        },
        {'one': 'pizza',
         'two': 'cake',
         'three': ['f', 'g', 'h', 'e'],
         'four': 'bar'
        }
       ]

letters = ['q', 'w', 'e', 'r','t','y']

dedup_rows = [row for row in dicts if row['three'][3] not in letters]

目标是dedup_rows应该包含dicts其中存储的列表的第四个元素three不包含在列表中的元素letters。本质上,delete row from dicts if row['three'][3] in letters. 上述代码的输出将是:

dedup_rows: [
             {'one': 'hello',
              'two': 'world',
              'three': ['a', 'b', 'c', 'd'],
              'four': 'foo'
             }
            ]

我拥有的代码正在运行,但实际上两者都dicts包含letters数十万个元素,因此执行速度很慢,因为每次迭代dicts还需要完整的迭代letters

在 Python 中有更优化的方法吗?

标签: pythonpython-3.x

解决方案


您的代码dedup_rows = [row for row in dicts if row['three'][3] not in letters]具有平方复杂性。因为它对. dicts_ 如果您的两个列表都包含大量元素。您应该考虑查找时间复杂度为 1 的数据结构。对于您的情况, Python 集是完美的。你可以阅读更多关于它的信息。 您需要做的就是转换为带有语法的集合并使用语法查找。lettersdicts

letters = ['q', 'w', 'e', 'r','t','y']set(letters)x in letters_set

dicts = [
    {'one': 'hello',
     'two': 'world',
     'three': ['a', 'b', 'c', 'd'],
     'four': 'foo'
    },
    {'one': 'pizza',
     'two': 'cake',
     'three': ['f', 'g', 'h', 'e'],
     'four': 'bar'
    }
   ]

letters = ['q', 'w', 'e', 'r','t','y']
letters_set = set(letters)

dedup_rows = [row for row in dicts if row['three'][3] not in letters_set]

像这样,您可以将算法从 n 平方的顺序更改为 n 的顺序。


推荐阅读