python - 使用python按类成员对字典进行排序
问题描述
我有以下代码
class Test:
def __init__(self,a ,b):
self.a=a
self.b=b
l= {}
myObj1 =Test(1,2)
myObj2 =Test(3,4)
l[1]=myObj1
l[2]=myObj2
如何按班级l
成员对字典进行排序b
Test
我已经尝试过l= sorted (l.items() , key = lambda x:x[1].b , reverse =True)
,但是当我尝试打印时print (l[1].b)
出现错误
Traceback (most recent call last):
File "l.py", line 13, in <module>
print (l[1].b)
AttributeError: 'tuple' object has no attribute 'b'
所以我的排序损坏了我的列表。
解决方案
蟒蛇> = 3.7
d_unsorted = {1: Test(1,2), 2: Test(3,4), 3: Test(0,5), 4:Test(6,-1)}
d_sorted = dict(sorted(d_unsorted.items(), key=lambda item: item[1].b))
参考:
推荐阅读
- multithreading - 无法跨具有 mpsc::Sender 作为字段的线程发送结构
- python - 在 AMBER 套件环境中运行 Python 脚本的问题
- python - 如何使用 python pandas 为 url、api 和日期约束编写一个 for 循环
- java - TypeMappingException:检测到具有不同返回类型的操作“opName”的多个方法
- docker - 将 CI 容器中的卷挂载到 docker-compose 容器中
- android - 在 rxjava 中订阅消费者?
- api-design - 如何在 Qlik Sense 中创建一个触发成功任务的任务
- android - 找不到 com.android.tools.build:gradle:3.6.2
- excel - 根据标题和前列设置单元格范围值
- python - Pyomo:使用两个索引初始化变量