1 python dictionary filter data-science
这是我的代码:
import csv
import os
filename = "StudentsPerformance.csv"
file = open(filename, "r", encoding="utf-8")
contents = csv.reader(file)
students = []
column_names = next(contents)
for row in contents:
student = {
"gender": row[0],
"race/ethnicity": row[1],
"parental level of education": row[2],
"lunch": row[3],
"test preparation course": row[4],
"math score": row[5],
"reading score": row[6],
"writing score": row[7],
}
students.append(student)
def math_scores(student):
return int(student["math score"])
def average_math_scores(student):
scores = list(map(math_scores, students))
total_scores = sum(scores)
number_of_scores = len(scores)
average_scores = total_scores / number_of_scores
print(average_scores)
return average_scores
if __name__ == '__main__':
average_math_scores(students)
Run Code Online (Sandbox Code Playgroud)
我怎样才能制作一个过滤器,以便男性和女性得到自己的字典。这样我就有一个字典,其中包含所有数据,称为女性,男性的数据也相同。我已经定义了称为“女性”和“男性”的两个字典。
小智 5
使用python3
我假设这是您的数据,代码也应该适用于更多字段:
students=[{"gender":'m',"math_score":'A'},
{"gender":'f',"math_score":'B'},
{"gender":'m',"math_score":'D'},
{"gender":'f',"math_score":'C'}]
Run Code Online (Sandbox Code Playgroud)
您可以使用内置filter函数:
males=list(filter(lambda x:x["gender"]=='m',students))
females=list(filter(lambda x:x["gender"]=='f',students))
Run Code Online (Sandbox Code Playgroud)
请参阅过滤器功能的文档。