简体   繁体   English

TypeError:字符串索引必须是整数-Python

[英]TypeError: string indices must be integers - Python

I've found an "TypError" and I don't know how to solve it anymore. 我发现了一个“ TypError”,我不知道该如何解决了。 Please, some help. 请帮忙。 I'll really appreciate an explanation if is possible. 如果可能的话,我将不胜感激。

My code: 我的代码:

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

Error: 错误:

; ; exit; 出口; {u'text': u'Sample data', 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 (most recent call last): File "/Users/macme/Documents/Python/test_Json.py", line 61, in value = item["subjects"][0]["quant"] TypeError: string indices must be integers logout Saving session... ...copying shared history... ...saving history...truncating history files... ...completed. {u'text':u'Sample data',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'}]}追溯(最近一次通话最近):文件“ /Users/macme/Documents/Python/test_Json.py”,第61行,其值= item [“ subjects”] [0] [“ quant”] TypeError:字符串索引必须为整数注销正在保存会话...正在复制共享历史记录...正在保存历史记录...截断历史记录文件...已完成。

[Process completed] [处理完成]

info is a dict but you're iterating it like a list. info是一个字典,但您要像列表一样对其进行迭代。 I think you want to iterate on info['subjects'] . 我认为您想迭代info['subjects']

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

Your for loop is not working how you think it does. 您的for循环无法正常工作。

for item in info loops over the keys of your dictionary, ie over 'text' and 'subjects'. for item in info字典的键上循环,即在“文本”和“主题”上循环。 Then you try do index into these strings with another string, which is bound to fail. 然后,您尝试使用另一个字符串将这些字符串编入索引,这肯定会失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM