伙计们我刚刚开始学习Python ..我对它没有深刻的了解。我陷入了这个List和Dictionaries相关的问题..它向我显示了一条错误消息。 错误O / P和代码在下面给出..
Error:
Traceback (most recent call last):
File "python", line 48, in <module>
File "python", line 45, in get_class_average
File "python", line 25, in get_average
TypeError: list indices must be integers, not st
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 = float(sum(numbers))/len(numbers)
return total
def get_average(student):
homework = average(student['homework'])
quizzes = average(student['quizzes'])
tests = average(student['tests'])
return 0.1*homework + \
0.3*quizzes + \
0.6*tests
def get_letter_grade(score):
if score>=90:
return "A"
elif score>=80:
return "B"
elif score>=70:
return "C"
elif score>=60:
return "D"
else:
return "F"
get_letter_grade(get_average(lloyd))
def get_class_average(students):
results=[];
results.append(get_average(students));
return average(results)
sts=[lloyd,alice,tyler];
get_class_average(sts)
答案 0 :(得分:1)
results.append(get_average(students))
应该迭代列表,因为get_average
需要dict
。替换为:
for student in students:
results.append(get_average(student))
或者简单地说:
def get_class_average(students):
results = [get_average(student) for student in students]
return average(results)
答案 1 :(得分:0)
您的students
变量是一个包含三名学生的列表(呃......三个词典)。
执行results.append(get_average(students));
时,您将该列表传递给get_average
方法,名为student
的参数(但在get_average
范围内,仍然是get_average
列表,因为参数的名称无关紧要)
然后,在student['homework']
中,您尝试将列表作为student
进行访问。由于def get_class_average(students):
results=[];
for student in students:
results.append(get_average(student));
return average(results)
参数是一个列表,这就是你得到错误的原因。
你可能想做这样的事情吗?
static class Extensions
{
public static void Sort<T, TKey>(this ObservableCollection<T> collection, Func<ObservableCollection<T>, TKey> sort)
{
var sorted = (sort.Invoke(collection) as IOrderedEnumerable<T>).ToArray();
for (int i = 0; i < sorted.Count(); i++)
collection.Move(collection.IndexOf(sorted[i]), i);
}
}
编辑(根据OP对此答案的评论):
我认为好的资源可以是this和this(还有更多Googling python lists dictionaries)