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

Python 排序

  •  
  •   88 · 2015-05-09 17:23:28 +08:00 · 2643 次点击
    这是一个创建于 3273 天前的主题,其中的信息可能已经有所发展或是发生改变。

    想对一个列表进行排序,比较规则如下:
    '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]。不知道问题出在哪。。。

    第 1 条附言  ·  2015-05-09 18:07:18 +08:00
    已解决,背景见
    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 条回复    2015-05-09 23:11:54 +08:00
    imn1
        1
    imn1  
       2015-05-09 17:27:01 +08:00
    真是恰巧遇上刚刚
    /t/189719 几位关于Q4的讨论
    Valyrian
        2
    Valyrian  
       2015-05-09 17:35:24 +08:00
    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
       2015-05-09 18:07:41 +08:00
    @Valyrian 已解决,谢谢。
    9hills
        4
    9hills  
       2015-05-09 18:42:48 +08:00
    cmp=lambda x, y: int(x + y) - int(y + x) 这个很赞。。
    xavierskip
        5
    xavierskip  
       2015-05-09 23:11:54 +08:00
    sorted 中 cmp参数的用法都没有搞清楚
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2170 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 16:13 · PVG 00:13 · LAX 09:13 · JFK 12:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.