Hri*_*ngh 0 python lambda dictionary python-3.x
我有一个表格如下:-
table = {
('A', 10): 'student1',
('B', 12): 'student4',
('C', 11): 'student3',
('D', 11): 'student2',
('E', 9): 'student5'
}
Run Code Online (Sandbox Code Playgroud)
我想按元组的第二项对该表进行排序(不需要就地)。
预期输出:-
table = {
('E', 9): 'student5'
('A', 10): 'student1',
('C', 11): 'student3',
('D', 11): 'student2',
('B', 12): 'student4',
}
Run Code Online (Sandbox Code Playgroud)
items()
排序后从原始元组列表重新创建字典:
table = {
('A', 10): 'student1',
('B', 12): 'student4',
('C', 11): 'student3',
('D', 11): 'student2',
('E', 9): 'student5'
}
table = dict(sorted(table.items(), key=lambda x: x[0][1]))
print(table)
Run Code Online (Sandbox Code Playgroud)
结果:
{('E', 9): 'student5', ('A', 10): 'student1', ('C', 11): 'student3', ('D', 11): 'student2', ('B', 12): 'student4'}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
43 次 |
最近记录: |