简体   繁体   English

如何解决这个TypeError:字符串索引必须是整数?

[英]How to solve this TypeError: string indices must be integers?

I'm new to python and may not be very familiar with the detailed syntax rules. 我是python的新手,可能对详细的语法规则不太熟悉。

Can i know how this error can be solved? 我能知道如何解决此错误吗? It points to line 6,7,8 and i'm not sure what went wrong. 它指向第6、7、8行,我不确定出了什么问题。 Thanks! 谢谢!

def calculate_average_expenditure(a):
    totalincome = 0
    totalsavings = 0
    count = 0
    for item in a:
        if (item['AGE2011'] >= 20 and item['AGE2011'] <= 30):
            totalincome += item['INC2011']
            totalsavings += item['SAV2011']
            count += 1

    totalexpenditure = totalincome-totalsavings
    return totalexpenditure/count

EDIT: Thanks, i got it working by tweaking how the method is called. 编辑:谢谢,我通过调整方法的调用方式使其工作。

a={ 'uen': 's1234567h', 'AGE2011':21, 'INC2011':100, 'SAV2011':80}
b={ 'uen': 's1234567h', 'AGE2011':28, 'INC2011':300, 'SAV2011':100}
x=[a,b]
calculate_average_expenditure(x)

I guess the parameter a is bound to a list of strings. 我猜参数a绑定到字符串列表。 Can you show how you call calculate_average_expenditure(...) and and what ... contains? 您可以显示如何调用calculate_average_expenditure(...) ,以及...包含什么吗?

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

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