【问题标题】:TypeError: list indices must be integers or slices, not str WITH APITypeError:列表索引必须是整数或切片,而不是 str WITH API
【发布时间】:2021-07-07 21:30:04
【问题描述】:
result = [{'line': 'johannsasuke@gmail.com:42ab89', 'sources': ['Taringa.net'], 'last_breach': '2017-08'}, {'line': 'johannsasuke@gmail.com:PEIN12345', 'sources': ['Evony.com'], 'last_breach': '2016-07'}, {'line': 'johannsasuke@gmail.com:sasuke12345', 'sources': ['Animoto.com', 'Collection 1', 'xSplit'], 'last_breach': '2019-01'}, {'line': 'johannsasuke@gmail.com', 'sources': ['xSplit'], 'last_breach': '2013-11', 'email_only': 1}]

for x in result:

   if result['email_only']==1:

     pass

   else:

     print(result['line'])

我正在尝试打印使用此 api 发布的组合,但出现 TypeError:列表索引必须是整数或切片,而不是 str。请帮忙!

【问题讨论】:

    标签: python json list api


    【解决方案1】:

    result 是一个列表,所以您的意思可能是x,因为这是您的项目:

    for x in result:
        if x.get("email_only") == 1:
            continue
        print(x["line"])
    

    打印:

    johannsasuke@gmail.com:42ab89
    johannsasuke@gmail.com:PEIN12345
    johannsasuke@gmail.com:sasuke12345
    

    注意:我使用了x.get(),因为如果字典中不存在键email_only(不抛出异常),它会返回None

    【讨论】:

    • @NathanWilliamson,注意使用continue 而不是pass。这是for 循环的约定。
    猜你喜欢
    • 2015-12-09
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 2018-10-13
    相关资源
    最近更新 更多