![](/img/trans.png)
[英]check if an element from a list exists in a strings of a txt file (not working) Python
[英]My python code to check for element exists in a list is not working
我有一个695 records
的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'), ...
]
使用是否有列表的短包含功能? 并循环我的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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.