Python比较两个列表,卡在里面试试看

2024-09-24 22:28:41 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我一直在尝试做一个监视器,比较两个列表-旧列表和新列表,旧列表保存当前保存的json文件,新列表检查是否有添加的新项,它会将它添加到新列表中

Json码:

sample = {
    "threads": [
        {
            "seoTitle": "used cfood",
            "other_crap": "yeet"
        },
        {
            "seoTitle": "trucks",
            "other_crap": "it's a fox!"

        },
        {
            "seoTitle": "rockets",
            "other_crap": "i'm rocket man"
        },
        {
            "seoTitle": "helicopter",
            "other_crap": "for 007",
            "price": {
              "currentRetailPrice": 1249.95
            }
        }
    ]
}

代码:

old_list = []

    while True:
        try:
            url = 'www.helloworld.com'
            resp = s.get(url)

            new_list = resp.json()['threads']

            for item in new_list:
                if item['seoTitle'] not in old_list:
                    try:

                        print(item['seoTitle']) 
                        print('item['other_crap']))  # Print other information
                        old_list.append(item['seoTitle'])


                    except Exception as e:
                        print(e)
                        print("ERROR")
                        time.sleep(5)
                        continue

            else:
                logger.warn("No new link found!")
                time.sleep(5)

        except Exception as e:
            print(e)
            continue

我注意到的问题是,我认为程序应该对我在上做的两个列表进行比较:

for item in new_list:
    if item['seoTitle'] not in old_list:

但问题是每次它检查比较时,它都会进入try方法,每次都会出现stucks,我认为这是不正确的。它应该做的是,它没有什么新的东西,那么它应该只做别的方法,我做错了什么?你知道吗

----每次打印

 print(item['seoTitle']) 
 print('item['other_crap']))  # Print other information

每次而不是去其他:方法。你知道吗


Tags: 方法injson列表newforitemold
1条回答
网友
1楼 · 发布于 2024-09-24 22:28:41

我认为它不会卡在try/except里。我认为它执行了附加操作,然后循环回到顶部,由于网络通信发生了一些问题而被卡住,所以它只是挂起等待服务器。很有可能。你知道吗

但是你对你观察到的东西不是很精确,所以很难说。我们也不知道你用什么连接到服务器,这让事情变得棘手。什么是s?您可以设置套接字超时,使其在特定时间后返回,而不会永远挂起。你知道吗

s.get(url)打印语句会有所帮助。另外,如果你展示了实际的输出也会有所帮助。你知道吗

相关问题 更多 >