簡體   English   中英

如何在帶有 if 語句的枚舉 for 循環中使用索引(python)

[英]How to use the index in an enumerate for loop with if statement (python)

我有一個嵌套字典,其中可以訪問這樣的值:

print(list['sublist'][0]['item'][0]['commentId'])

但是,如果我創建一個 for 循環並想使用這樣的索引,它會給我一個 keyerror:

    for index,sublist in enumerate(list['sublist']):
        if sublist[index]['item'][0]['commentId'] == commentid:
            number = sublist[index]['item'][0]['positionId']
            username = sublist[index]['subListCreator']
    print(number)
    print(username)

錯誤:

, in send_async_notification
    if sublist[index]['item'][0]['commentId'] == commentid:
  File "/Users/ ...... /venv/lib/python3.8/site-packages/mongoengine/base/document.py", line 263, in __getitem__
    raise KeyError(name)

本練習的全部目標是根據更深的嵌套 commentId 在嵌套數組中獲取兩個特定值。 如果有匹配,我想知道它下面的 positionId 和 subListCreator。 一個項目只能有一個commentId,因此代碼中的[0]。

也可以只使用與commentId 匹配的整個字典“分支”,這也可以使事情正常進行。

順便說一句, print(commentid)給了我想要匹配的 commentid。 只是為了解釋它的現在。

希望這里有一個解決方案,想知道為什么它不起作用。 期待任何答案!

感謝 Mathias 的評論:雙 for 循環解決了我的問題:

    for sublist in list['sublist']:
        for item in sublist['item']:
            if item['commentId'] == commentid:
                number = item['positionId']
                username = sublist['subListCreator']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM