python - 如果 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 中有更优化的方法吗?
解决方案
您的代码dedup_rows = [row for row in dicts if row['three'][3] not in letters]
具有平方复杂性。因为它对. dicts
_ 如果您的两个列表都包含大量元素。您应该考虑查找时间复杂度为 1 的数据结构。对于您的情况, Python 集是完美的。你可以阅读更多关于它的信息。
您需要做的就是转换为带有语法的集合并使用语法查找。letters
dicts
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 的顺序。
推荐阅读
- html - Can't remove cell spacing between cells in table html css
- liquid - Liquid : 如何在日期上进行数学运算?
- statistics - 如何计算置信区间和样本量
- javascript - 将数组分配给另一个数组时出现角度未定义错误
- django - 为什么我们在初始化 celery 应用程序时使用本地文件设置
- linux - OpenCL 支持 Intel CPU 和 Nvidia GPU
- emacs - 如何以及在何处为 Ubuntu 18 上的 sbcl / slime / emacs 设置默认加载位置
- autodesk-forge - 执行工作项“找不到插件文件”时出错
- python - 美汤这种格式的数据怎么搜?
- regex - 我正在尝试为接受的符号和字符串列表创建一个正则表达式