猿问

如何在省略某些数据的同时获取一组 JSON 数据?

我有一个 json 数据,其中包含一系列 SAT 分数及其相应的学校。


输入: [{"num_of_sat_test_takers":"s","sat_critical_reading_avg_score":"s","sat_math_avg_score":"s","sat_writing_avg_score":"s","school_name":"HUDSON HIGH SCHOOL OF LEARNING TECHNOLOGIES"}, {"num_of_sat_test_takers":"91","sat_critical_reading_avg_score":"383","sat_math_avg_score":"423","sat_writing_avg_score":"366","school_name":"UNIVERSITY NEIGHBORHOOD HIGH SCHOOL"}, {num_of_sat_test_takers":"70","sat_critical_reading_avg_score":"377","sat_math_avg_score":"402","sat_writing_avg_score":"370","school_name":"EAST SIDE COMMUNITY SCHOOL"}]


预期输出: "[[383, 423, 366, "UNIVERSITY NEIGHBORHOOD HIGH SCHOOL"], [377, 402, 370, "EAST SIDE COMMUNITY SCHOOL"]]"


我只想采用由 SAT 阅读分数、SAT 数学分数、SAT 写作分数和相应学校名称组成的数组,同时省略不包含任何有效 SAT 分数的学校,例如“HUDSON HIGH SCHOOL OF LEARNING TECHNOLOGIES” . 这是我的尝试。现在我如何省略不包含任何有效 SAT 成绩的学校?


def keyData(data):

    json_str = [[float(e["sat_critical_reading_avg_score"]), 

    float(e["sat_math_avg_score"]), float(e["sat_writing_avg_score"]), 

    e["school_name"]] for e in data]

    return json.dumps(json_str)


犯罪嫌疑人X
浏览 140回答 1
1回答

慕斯709654

这应该做:def keyData(data):  result = []  for ele in data:    try:      result.append([        int(ele['sat_critical_reading_avg_score']),        int(ele['sat_math_avg_score']),        int(ele['sat_writing_avg_score']),        ele['school_name']      ])    except:      pass  return result如果element没有定义任何属性或值不是整数,则会抛出错误,附加不会发生并且执行将跳转到except块,在那里什么也不会发生,我们对所有重复此操作数据中的元素。
随时随地看视频慕课网APP

相关分类

Python
我要回答