TypeError: 'NoneType' object is not iterable

报错原因:对 None 进行迭代

 

d = {"aa": "1", "bb": "2", "cc": "345"}
d2 = {"aa": "12", "bb": "02"}

l1 = [d, d2]

for item in l1:
    x = item.get("cc")
    if "3" not in x:
        print(x)

报错:TypeError: 'NoneType' object is not iterable

 

解决:

d2 没有 key 为 “cc”   所以 x 可能为 None  对None 进行迭代 会报错

d = {"aa": "1", "bb": "2", "cc": "345"}
d2 = {"aa": "12", "bb": "02"}

l1 = [d, d2]

for item in l1:
    x = item.get("cc")
    if x and "3" not in x:
        print(x)

 

posted @ 2022-03-21 13:18  半日闲1  阅读(868)  评论(0)    收藏  举报