list = [ {'student_name': zhangsan, 'student_score': 65}, {'student_name': lisi, 'student_score': 95}, {'student_name': wangwu, 'student_score': 80}, {'student_name': maliu, 'student_score': 75}, {'student_name': zhuqi, 'student_score': 88} ]
把 5 个学生成绩从高到低排序,取前三名,要怎么处理这样的 list ?
1
aaronzjw 2016 年 11 月 13 日 via Android
sort+lambda
|
2
justou 2016 年 11 月 13 日 from operator import itemgetter
lst = [ {'student_name': 'zhangsan', 'student_score': 65}, {'student_name': 'lisi', 'student_score': 95}, {'student_name': 'wangwu', 'student_score': 80}, {'student_name': 'maliu', 'student_score': 75}, {'student_name': 'zhuqi', 'student_score': 88} ] top3 = sorted(lst, key=itemgetter('student_score'), reverse=True)[:3] print top3 |
3
rogwan OP |
4
pupboss 2016 年 11 月 13 日
def score(s):
return s['student_score'] bar = sorted(foo, key = score) print(bar) |
6
aaronzjw 2016 年 11 月 13 日
@rogwan print sorted(list, key=lambda student: student['student_score'])[-3:]
|
7
Mutoo 2016 年 11 月 13 日 [:3] 这个表情好搞笑
|
8
ipconfiger 2016 年 11 月 13 日
@rogwan 居然还有这种书
|
9
triostones 2016 年 11 月 13 日
In [12]: import heapq
In [13]: from operator import itemgetter In [14]: scores = [ {'student_name': 'zhangsan', 'student_score': 65}, {'student_name': 'lisi', 'student_score': 95}, {'student_name':'wangwu', 'student_score': 80}, {'student_name': 'maliu', 'student_sco ...: re': 75}, {'student_name': 'zhuqi', 'student_score': 88} ] In [15]: heapq.nlargest(3, scores, key=itemgetter('student_score')) Out[15]: [{'student_name': 'lisi', 'student_score': 95}, {'student_name': 'zhuqi', 'student_score': 88}, {'student_name': 'wangwu', 'student_score': 80}] |
10
rogwan OP @ipconfiger 就是 Python 核心编程那本书啊
|
11
rogwan OP @triostones 谢谢,这个方法也 OK ^-^
|
12
staticor 2016 年 11 月 13 日
python cookbook 里肯定是提了 第 1 章.
|
14
timeship 2016 年 11 月 13 日
楼上正确, sorted ( list, key=itemgetter )然后取前三个,好像很多书里都有讲过类似的 QAQ
|
15
gemini 2016 年 11 月 14 日
top3 = sorted(list, key=lambda stu:int(stu['student_score']), reverse=True)[0:3]
|
16
ericls 2016 年 11 月 14 日
lst = [ {'student_name': 'zhangsan', 'student_score': 65},
{'student_name': 'lisi', 'student_score': 95}, {'student_name': 'wangwu', 'student_score': 80}, {'student_name': 'maliu', 'student_score': 75}, {'student_name': 'zhuqi', 'student_score': 88} ] sorted(lst, key=lambda stu: stu["student_score"], reverse=True)[:3] 明明就可以 |
18
hl 2016 年 11 月 14 日
请大家参考 python 官方高级数据结构 heapq 章节,可以使用内置高效的方法来最简单的实现
students_list = [ {'student_name': 'zhangsan', 'student_score': 65}, {'student_name': 'lisi', 'student_score': 95}, {'student_name': 'wangwu', 'student_score': 80}, {'student_name': 'maliu', 'student_score': 75}, {'student_name': 'zhuqi', 'student_score': 88} ] #################### import heapq score_first_3 = heapq.nlargest(3,students_list,key=lambda student:student["student_score"]) print score_first_3 #################### |
19
jayyjh 2016 年 11 月 14 日
sorted_dict = sorted(dict.items(), key=lambda item: item[1])
|