V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
dwadewyp
V2EX  ›  Python

Python list 中的字段,想根据 value 中的一个 key 排序,如下代码,有什么优雅的写法么

  •  
  •   dwadewyp · 2020-12-04 17:52:38 +08:00 · 2112 次点击
    这是一个创建于 1231 天前的主题,其中的信息可能已经有所发展或是发生改变。

    rd = [{100: {"id": 1, "name": "wade", "code": "abc", "is_analysis": 1}}, {101: {"id": 2, "name": "lebron", "code": "abc", "is_analysis": 2}}, {102: {"id": 3, "name": "cp3", "code": "abc", "is_analysis": 0}}] 根据 is_analysis 来排序,有什么优雅的写法么

    9 条回复    2020-12-07 18:35:41 +08:00
    woostundy
        1
    woostundy  
       2020-12-04 18:01:30 +08:00
    sorted(rd, key=lambda x:x[is_analysis])
    lIlIlIlI
        2
    lIlIlIlI  
       2020-12-04 18:01:44 +08:00
    如果你保证 dict 只有一个 key 的话
    rd.sort(key=lambda x:x.values()[0]['is_analysis'])
    snachx
        3
    snachx  
       2020-12-04 18:02:14 +08:00
    rd.sort(key=lambda item: list(item.values())[0]['is_analysis'])
    wuwukai007
        4
    wuwukai007  
       2020-12-04 21:51:35 +08:00 via Android
    一楼明显不对🙄
    hengstchon
        5
    hengstchon  
       2020-12-04 22:21:02 +08:00   ❤️ 1
    我是蜻蜓队长,我宣布 1 楼和 2 楼不对,3 楼正确。
    fasionchan
        6
    fasionchan  
       2020-12-05 13:04:25 +08:00
    或许花点时间,停下来思考一下,这样的数据结构设计是否合理,会有更好的想法🤔
    l4ever
        7
    l4ever  
       2020-12-05 15:36:07 +08:00
    这样的结构简直莫名其妙
    noparking188
        8
    noparking188  
       2020-12-05 20:28:07 +08:00
    兄弟,这么复杂的字典数据上 dataclasses 叭
    shm7
        9
    shm7  
       2020-12-07 18:35:41 +08:00 via iPhone
    以后可能会有问 print string 的写法的了 % {} 还是 fstring 。坐等
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5149 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 08:18 · PVG 16:18 · LAX 01:18 · JFK 04:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.