gpt4 book ai didi

python - 我用于检查列表中是否存在元素的 python 代码不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 11:12:57 24 4
gpt4 key购买 nike

我有一个包含 695 条 记录 的 SQL 查询结果,我需要删除与 _ids 列表中的 52 个项目的匹配项。

_ids = [44226, 44303, ...]

records = [
(44226, datetime.datetime(2019, 8, 27, 10, 0), datetime.datetime(2019,
8, 27, 21, 0), '0.50'),
(44227, datetime.datetime(2019, 8, 30, 18, 0), datetime.datetime(2019,
8, 30, 22, 30), '0'), ...
]

使用 Is there a short contains function for lists?循环遍历我的 records 总是得到 True

for i in records:
if i[0] not in _ids:
# pop from list

有什么建议可以有效地返回仅列出与 _ids 列表匹配的记录列表?

最佳答案

从您的评论来看,您正在循环内调用 .pop()。这将在迭代列表的同时修改列表,从而导致意外结果。试试这个:

import datetime 

_ids = [44226, 44303]

records = [
(44226, datetime.datetime(2019, 8, 27, 10, 0), datetime.datetime(2019,
8, 27, 21, 0), '0.50'),
(44227, datetime.datetime(2019, 8, 30, 18, 0), datetime.datetime(2019,
8, 30, 22, 30), '0'),
]

print([row[0] for row in records if row[0] in _ids])

这使用条件列表理解仅返回匹配的 id

更新:对此答案的编辑请求指出,将 _ids 定义为 set 是一个好主意,这样您就可以在查找中拥有恒定的时间复杂度,即:

_ids = {44226, 44303}

关于python - 我用于检查列表中是否存在元素的 python 代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57750300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com