为什么我一直得到'字符串索引必须是整数'错误?

时间:2017-12-26 17:33:09

标签: python

我是Python新手,我试图扩展Codecademy的编码练习。我希望程序为所选学生的平均值提供用户输入,但我不断得到'字符串索引必须是整数'错误。

lloyd = {
  "name": "Lloyd",
  "homework": [90.0, 97.0, 75.0, 92.0],
  "quizzes": [88.0, 40.0, 94.0],
  "tests": [75.0, 90.0]
}
alice = {
  "name": "Alice",
  "homework": [100.0, 92.0, 98.0, 100.0],
  "quizzes": [82.0, 83.0, 91.0],
  "tests": [89.0, 97.0]
}
tyler = {
  "name": "Tyler",
  "homework": [0.0, 87.0, 75.0, 22.0],
  "quizzes": [0.0, 75.0, 78.0],
  "tests": [100.0, 100.0]
}

def average(numbers):
  total = sum(numbers)
  total = float(total)/len(numbers)
  return total

#List of Students to choose from for get_average input()
x = '1. Alice'
y = '2. Tyler'
z = '3. Lloyd'
#get_average function
def get_average(alice): 
    homework = average(alice['homework'])
    quizzes = average(alice['quizzes']) 
    tests = average(alice['tests'])
    student = input('Please type the number of the student who\'s weighted average you would like to see:' + '\n' + x + '\n' + y + '\n' + z)
    if student == '1':
      print( 0.1 * average(alice['homework']) + 0.3 * average(alice['quizzes']) + 0.6 * average(alice['tests']) )

get_average('student')

我打算使用爱丽丝平均值的代码为Lloyd和Tyler的平均值创建一个函数,但我无法想出第一部分。有人能帮我吗?感谢。

1 个答案:

答案 0 :(得分:0)

自由做出一些改变。首先:您可以将数据放入带字典的数组中。名称位于键名称下的数组数据中。

我们将使用标准库中的两个函数。从textwrap开始,正确地格式化文本,并从统计学中计算平均值。

// service.ts
generate(str): string {
    const h = Md5.hashStr(str);
    return h;
}

// component.ts
this.hash = this.hashService.generate(this.form.value.password);

data = [{
  "name": "Lloyd",
  "homework": [90.0, 97.0, 75.0, 92.0],
  "quizzes": [88.0, 40.0, 94.0],
  "tests": [75.0, 90.0]
    },
  {
  "name": "Alice",
  "homework": [100.0, 92.0, 98.0, 100.0],
  "quizzes": [82.0, 83.0, 91.0],
  "tests": [89.0, 97.0]
  },
    {
  "name": "Tyler",
  "homework": [0.0, 87.0, 75.0, 22.0],
  "quizzes": [0.0, 75.0, 78.0],
  "tests": [100.0, 100.0]
}]