【问题标题】:TypeError: string indices must be integers - PythonTypeError:字符串索引必须是整数 - Python
【发布时间】:2016-03-26 04:07:39
【问题描述】:

我发现了一个“TypError”,但我不知道如何解决它了。请帮忙。如果可能的话,我将非常感谢您的解释。

我的代码:

import json

input = '''{
  "text":"Sample data",
  "subjects":[
    {
      "id":"A",
      "quant":10
    },
    {
      "id":"B",
      "quant":9
    },
    {
      "id":"C",
      "quant":8
    },
    {
      "id":"D",
      "quant":7
    },
    {
      "id":"E",
      "quant":6
    }]}
'''

info = json.loads(input)

count = 0
total = 0
for item in info:
    value = item["subjects"][0]["quant"]
    value = int(value)
    total += value
    count += count

print 'Count: ', count    
print 'Sum: ', total

错误:

;出口; {u'text': u'样本数据', u'subjects': [{u'quant': 10, u'id': u'A'}, {u'quant': 9, u'id': u'B'}, {u'quant': 8, u'id': u'C'}, {u'quant': 7, u'id': u'D'}, {u'quant': 6, u'id': u'E'}]} Traceback (最近一次通话最后):文件 "/Users/macme/Documents/Python/test_Json.py", 第 61 行,在 value = item["subjects"][0]["quant"] TypeError: string indices must be integers logout Saving session... ...复制共享历史... ...保存历史记录...截断历史记录文件... ...已完成。

[处理完成]

【问题讨论】:

  • 对错误框格式表示抱歉。

标签: python json dictionary


【解决方案1】:

您的 for 循环没有按照您的想法工作。

for item in info 循环遍历字典的键,即遍历“文本”和“主题”。然后你尝试用另一个字符串索引这些字符串,这肯定会失败。

【讨论】:

    【解决方案2】:

    info 是一个字典,但您正在像列表一样迭代它。我想你想迭代info['subjects']

    for item in info['subjects']:
      value = int(item['quant'])
    

    【讨论】:

    • 谢谢你,丹。你真的帮了我,因为现在我明白了为什么会出现这个错误。非常感谢!
    猜你喜欢
    • 2016-02-17
    • 2023-03-03
    • 1970-01-01
    • 2022-11-02
    • 2019-04-26
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多