推荐学习书目
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 · May 13, 2019 · 1802 views
    This topic created in 2584 days ago, the information mentioned may be changed or developed.

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

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

    请问该如何写,谢谢。

    1 replies    2019-05-13 16:58:53 +08:00
    xpresslink
        1
    xpresslink  
       May 13, 2019
    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')]
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1053 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 22:40 · PVG 06:40 · LAX 15:40 · JFK 18:40
    ♥ Do have faith in what you're doing.