简体   繁体   English

Python-在列表中查找列表得分的平均值

[英]Python - Finding the average of scores of a list in a list

I'm trying to find the average scores of a list in a list, using lambda. 我正在尝试使用lambda在列表中找到列表的平均分数。

Scores=[['James','Q',3,4,1,5],['Kat','S',3,4,1,2],['John','G',3,5,6,4]['Erikson','G',3,7,6,8],['Filip','NJ',3,8,9,9]]
sortedScores=sorted(Scores,key=lambda score:avg(score[3:],reverse=False))

for i in Scores:
    print(i[0:1],avg(i[3:]))

avg is not a command, so what would be the best way to calculate the average within this code? avg不是命令,那么在此代码中计算平均值的最佳方法是什么?

You forgot a comma, that's all: 您忘记了逗号,仅此而已:

Scores=[
    ['James','Q',3,4,1,5],
    ['Ryan','G',3,4,1,2],
    ['Klodiano','G',3,5,6,4]['Erikson','G',3,7,6,8],
    #                      ^^
    ['Filip','NJ',3,8,9,9]
]

Without the comma, the list ['Klodiano','G',3,5,6,4] is being indexed, but instead of an integer, you passed in the tuple ('Erikson','G',3,7,6,8) . 如果不使用逗号, ['Klodiano','G',3,5,6,4]为列表['Klodiano','G',3,5,6,4]编制索引,但是您传入了一个元组('Erikson','G',3,7,6,8)

Note that your sorted() list also has an error: 请注意,您的sorted()列表也有一个错误:

sortedScores=sorted(
    Scores,
    key=lambda score:avg(score[3:],reverse=False))
    #                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

You are passing in the reverse=False to the avg() callable, not to sorted() . 您正在将reverse=False传递给可调用的avg() ,而不是sorted() You probably wanted: 您可能想要:

sortedScores=sorted(
    Scores,
    key=lambda score:avg(score[3:]),
    reverse=False)

instead. 代替。

You don't need to slice if you wanted to print the name of each student separately; 如果要单独打印每个学生的姓名,则无需切片。 you'd use indexing instead: 您应该改用索引:

for i in Scores:
    print(i[0], avg(i[3:]))

And finally, the GCSE programming problem you are implementing asks for the last 3 scores, not for all scores except the first 1. You need to use -3 to slice of the last 3 scores to calculate the average: 最后,您正在实施的GCSE编程问题要求最后3个分数,而不是除前1个分数之外的所有分数。您需要使用-3来切入最后3个分数以计算平均值:

avg(score[-3:])

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

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