如何将字典列表与 python 中的列表进行比较

How to compare list of dicts with list in python

我正在从事一个计算机视觉项目,其中模型正在预测框架中的对象。我将所有对象附加到列表 detectedObjs 中。我必须为这些检测到的对象创建一个字典列表,其中包含对象的名称、开始时间和结束时间。开始时间基本上是指第一次检测到对象的时间,结束时间是指最后一次检测到对象的时间。为此,我有以下代码:

for obj in detectedObjs:
    if not objList:
        # First object is detected, save its information
        tmp = dict()
        tmp['Name'] = obj
        tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
        tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
        objList.append(tmp)    
    else:
        # Here check if the object is alreay present in objList
        # If yes, then keep updating end time
        # If no, then add the object information in objList
        for objDict in objList:
            if objDict['Name'] == obj:
                objDict["EndTime"] = datetime.datetime.utcnow().isoformat()
                break 
            else:
                tmp = dict()
                tmp['Name'] = obj
                tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
                tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
                objList.append(tmp)   

所以首先在 for 循环中我保存了第一个检测到的对象的信息。在那之后,我正在检查当前对象是否已经添加到 objList 中,如果是,则继续更新结束时间,否则,将其添加到 objList.

detectedObjs 列表有 item1,几秒钟后 item2 也被添加。但在 objList 的输出中,我可以看到 item1 已正确添加,但 item2 被添加了很多次。有什么方法可以优化此代码,以便我可以有正确的开始和结束时间。谢谢

下面是完整的可重现代码。我不能将模型的预测代码放在这里,所以我添加了一个线程,它将继续向 detectedObj 列表添加项目

from threading import Thread
import datetime
import time

detectedObjs = []

def doJob():
    global detectedObjs
    for i in range(2):
        if i == 0:
            detectedObjs.append("item1")
        elif i == 1:
            detectedObjs.append("item2")
        elif i == 2:
            detectedObjs.append("item3")
        elif i == 3:
            detectedObjs.remove("item1")
        elif i == 4:
            detectedObjs.remove("item2")
        elif i == 5:
            detectedObjs.remove("item3")
        time.sleep(3)

Thread(target=doJob).start()
while True:
    objList = []
    for obj in detectedObjs:
        if not objList:
            # First object is detected, save its information
            tmp = dict()
            tmp['Name'] = obj
            tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
            tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
            objList.append(tmp)
        else:
            # Here check if the object is alreay present in objList
            # If yes, then keep updating end time
            # If no, then add the object information in objList
            for objDict in objList:
                if objDict['Name'] == obj:
                    objDict["EndTime"] = datetime.datetime.utcnow().isoformat()
                    break
                else:
                    tmp = dict()
                    tmp['Name'] = obj
                    tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
                    tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
                    objList.append(tmp)
    print(objList)

我建议您使用包含字典的字典……这是您的代码的未经测试版本……

obj_dict = {}
for obj in detectedObjs:
    if obj not in obj_dict:  # checks the keys for membership
        # first entry
        time_seen = datetime.datetime.utcnow().isoformat()
        obj_dict[obj] = {
            “name”: obj,
            “start”: time_seen,
            “end”: time_seen,
        }
    else:  # additional time(s) seen
        time_seen = datetime.datetime.utcnow().isoformat()
        obj_dict[obj][“end”] = time_seen

此外,当您的列表变大时,这将节省处理时间,它不必每次都在整个列表中搜索条目来更新它。