推荐学习书目
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
88
V2EX  ›  Python

Python 排序

  •  
  •   88 · May 9, 2015 · 3700 views
    This topic created in 4044 days ago, the information mentioned may be changed or developed.

    想对一个列表进行排序,比较规则如下:
    '12'+'121' = '12121' > '12112' = '121' + '12',
    所以 12 > 121

    这是我写的代码:

    nums = [12, 121]
    print sorted(nums, cmp=lambda x, y: int(str(x) + str(y)) > int(str(y) + str(x)))
    

    输出为:[12, 121],而我想要的是[121, 12]。不知道问题出在哪。。。

    Supplement 1  ·  May 9, 2015
    已解决,背景见
    https://leetcode.com/problems/largest-number/
    http://v2ex.com/t/189719

    def largestNumber(self, nums):
    return str(int(''.join(sorted(map(str, nums), cmp=lambda x, y: int(x + y) - int(y + x), reverse=True))))
    5 replies    2015-05-09 23:11:54 +08:00
    imn1
        1
    imn1  
       May 9, 2015
    真是恰巧遇上刚刚
    /t/189719 几位关于Q4的讨论
    Valyrian
        2
    Valyrian  
       May 9, 2015
    cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.

    你的cmp返回的是True/False,他要的是数字。另外你的符号好像也反了。可以试下以下任意一个:
    ```
    cmp=lambda x, y: cmp(int(str(y) + str(x)), int(str(x) + str(y)))
    cmp=lambda x, y: int(str(y) + str(x)) - int(str(x) + str(y))
    ```

    顺便,这个比较的逻辑有什么含义么,完全无法理解。。
    88
        3
    88  
    OP
       May 9, 2015
    @Valyrian 已解决,谢谢。
    9hills
        4
    9hills  
       May 9, 2015
    cmp=lambda x, y: int(x + y) - int(y + x) 这个很赞。。
    C0VN
        5
    C0VN  
       May 9, 2015
    sorted 中 cmp参数的用法都没有搞清楚
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5322 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 672ms · UTC 08:34 · PVG 16:34 · LAX 01:34 · JFK 04:34
    ♥ Do have faith in what you're doing.