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
oldbird
V2EX  ›  Python

如何对多个字段按不同要求排序?

  •  
  •   oldbird · 2019-05-13 16:00:07 +08:00 · 1295 次点击
    这是一个创建于 1808 天前的主题,其中的信息可能已经有所发展或是发生改变。

    a=[('a',1,3,'f'),('b',1,2,'f'),('c',3,1,'m')]

    要求按 4 升序、1 降序、2 升序、3 降序的优先规则进行排序

    请问该如何写,谢谢。

    1 条回复    2019-05-13 16:58:53 +08:00
    xpresslink
        1
    xpresslink  
       2019-05-13 16:58:53 +08:00
    from functools import cmp_to_key

    def keyfunc(x,y):
    □□□□if x[3] > y[3]:
    □□□□□□□□return 1
    □□□□elif x[3] < y[3]:
    □□□□□□□□return -1
    □□□□elif x[0] < y[0]:
    □□□□□□□□return 1
    □□□□elif x[0] > y[0]:
    □□□□□□□□return -1
    □□□□elif x[1] > y[1]:
    □□□□□□□□return 1
    □□□□elif x[1] < y[1]:
    □□□□□□□□return -1
    □□□□elif x[2] < y[2]:
    □□□□□□□□return 1
    □□□□elif x[2] > y[2]:
    □□□□□□□□return -1
    □□□□else:
    □□□□□□□□return 0

    a=[('a',1,3,'f'),('b',1,2,'f'),('c',3,1,'m')]

    print(sorted(a, key=cmp_to_key(keyfunc)))

    # [('b', 1, 2, 'f'), ('a', 1, 3, 'f'), ('c', 3, 1, 'm')]
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5718 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 06:29 · PVG 14:29 · LAX 23:29 · JFK 02:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.