[英]count grade inside sublist of dictionary which is inside a list
i am fairly new to python, and i am learning how to loop through list, dictionaries tuples et... i made up this list with dictionaries and i want to know how to loop through the each dictionary and count the grades and add the sum of the grades together to know the total.我对 python 相当陌生,我正在学习如何循环遍历列表、字典元组等...我用字典组成了这个列表,我想知道如何遍历每个字典并计算成绩并相加的成绩一起知道总。 i have added my loop after the dictionary.
我在字典之后添加了我的循环。
students = [
{
'first_name': 'Carlos',
'last_name': 'Santiago',
'class':'French',
'grades': [
'A',
'B+',
'C'
]
},
{
'first_name': 'Dana',
'last_name': 'Lynn',
'class':'Spanish',
'grades': [
'D',
'A+',
'A',
'B'
]
},
{
'first_name': 'Fin',
'last_name': 'leroy',
'class':'Math',
'grades': [
'B',
'B+',
'A',
'A+',
'B'
]
}
]```
```sum =0
for i in students:
if i =='grades':
for v in students['grades']:
sum+=v
print(sum)```
for student in enumerate(students):
sum = 0
list_of_grades = student[1]['grades']
for grade in list_of_grades:
*Your code to add the grades goes here*
To print the sum (concatenation in your case) of the grades of each student:要打印每个学生的成绩总和(在您的情况下是串联):
for student in students:
sum = ''.join(student['grades'])
print(sum)
Example output:示例 output:
AB+C
summing strings concatenates them.求和字符串将它们连接起来。
If you change grades
to be something like:如果您将
grades
更改为:
'grades': [ 5, 7, 10, 3]
Then:然后:
for student in students:
sum = sum(student['grades'])
print(sum)
Outputs: 25
输出:
25
First, you want to avoid using built-in function names (eg, sum) as your object name.首先,您要避免使用内置 function 名称(例如 sum)作为您的 object 名称。
Second, I assume you meant to get the sum of integers or floats.其次,我假设您打算获得整数或浮点数的总和。 So I replaced your string grades with integers.
所以我用整数替换了你的字符串等级。
students_new = [
{
'first_name': 'Carlos',
'last_name': 'Santiago',
'class':'French',
'grades': [
1,
2,
3
]
},
{
'first_name': 'Dana',
'last_name': 'Lynn',
'class':'Spanish',
'grades': [
1,
2,
3,
4
]
},
{
'first_name': 'Fin',
'last_name': 'leroy',
'class':'Math',
'grades': [
1,
2,
3,
4,
5
]
}
]
total=0
for i in students_new:
i_sum = sum(i['grades'])
print(i['last_name'], i['class'], 'grade:', i_sum)
total+=i_sum
print(total)
IIUC, this can simply be done in a one liner using list comprehension en value_counts
: IIUC,这可以简单地使用列表理解 en
value_counts
在单行中完成:
pd.Series([g for l in [rec['grades'] for rec in students] for g in l]).value_counts()
Output: Output:
A 3
B 3
B+ 2
A+ 2
C 1
D 1
dtype: int64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.