代码之家  ›  专栏  ›  技术社区  ›  CDNthe2nd

Python-使用for循环通过json对象打印

  •  0
  • CDNthe2nd  · 技术社区  · 8 年前

    所以我一直在做一种显示器-什么显示器是每当一个新的项目,对象,数字是新的,然后打印出来基本上没有什么伤害。

    "threads": {
        "1": {
            "name": "Hello",
            "id": "4174"
        },
        "2": {
            "name": "World",
            "id": "6231"
        },
        "3": {
            "name": "Overflow",
            "id": "7231"
        }
    }
    

    def get_feed():
    
        url = 'https://www.helloworld.com/loadfilter'
        resp = s.get(url, timeout=6)
        resp.raise_for_status()
    
        return resp.json()['threads']
    
    old_list = []
    
    for index, thread in get_feed().items():
        old_list.append(thread['id'])
    
    while True:
        try:
    
            new_list = []
            for index, thread in get_feed().items():
                new_list.append(thread['id'])
    
            for index, item in enumerate(new_list):
                if item in old_list:
                    print(item['name'] # ERROR - string indices must be integers
    
            else:
                print('Sleeping 2 sec')
                time.sleep(2)
    
    
        except Exception as e:
            print(e)
    
    
    sys.exit()
    

    所以基本上如果我在 for index, thread in get_feed().items(): 印刷品 thread['name'] 这不是问题,它会打印出来。

    if item in old_list:

    意思是:每当我在 if item old list 等等,['name']它应该给出名字吗?

    2 回复  |  直到 8 年前
        1
  •  1
  •   Henry Woody    8 年前

    old_list 你只是附加了 id 每一个 thread name 的 线 对象 旧目录 new_list

    创建 旧目录 (注意不需要使用 for

    old_list = list(get_feed().values())
    

    创建 :

    new_list = list(get_feed().values())
    

    检查/打印:

    for thread in new_list:
        if thread in old_list:
            print(thread['name'])
    
        2
  •  1
  •   pekapa    8 年前

    你的 item thread['id'] name 不再。 您可以尝试将整个线程对象保存在列表中,而不仅仅是 id

    for index, thread in get_feed().items():
        new_list.append(thread)
    

    或者,正如“亨利的回答”中所建议的,没有循环:

    new_list = list(get_feed().values())
    


    item['id'] 是在 old_list 比 print (item['name']) thread 反对。

    (编辑:注意,这里,我们只检查 ,如果你回到@henry的建议,你会检查整个 线 ,包括它可能具有的每个属性)