【问题标题】:How to solve this TypeError: string indices must be integers?如何解决这个 TypeError: string indices must be integers?
【发布时间】:2012-03-03 18:02:41
【问题描述】:

我是python新手,可能对详细的语法规则不是很熟悉。

我能知道如何解决这个错误吗?它指向第 6,7,8 行,我不确定出了什么问题。谢谢!

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

编辑: 谢谢,我通过调整方法的调用方式让它工作了。

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)

【问题讨论】:

  • a 是什么? item 是什么类型(我猜是str)?你想做什么?
  • 看起来您的函数需要一系列映射(例如字典列表),但您正在传递其他内容。
  • 非常感谢!我让它以这种方式工作。 >>> 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) 110

标签: python dictionary typeerror


【解决方案1】:

我猜参数a 绑定到一个字符串列表。你能说明你如何称呼calculate_average_expenditure(...) 以及... 包含什么吗?

【讨论】:

  • 我有这些:>>> d={ 'uen': 's1234567h', 'AGE2011':21, 'INC2011':100, 'SAV2011':80} >>> calculate_average_expenditure(d ) 21 我正在从 java 转换,并尝试创建类似 ArrayList 的东西。谢谢!
  • 试试:calculate_average_expenditure([d]).
  • 非常感谢!我让它以这种方式工作。 >>> 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) 110
猜你喜欢
  • 2013-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-31
  • 2020-01-20
  • 2023-02-22
  • 2020-10-18
  • 1970-01-01
相关资源
最近更新 更多