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

求教一个 Python 的排序问题

  •  
  •   dreamtrail · 2016-10-02 11:03:45 +08:00 · 2881 次点击
    这是一个创建于 2734 天前的主题,其中的信息可能已经有所发展或是发生改变。

    python 学的比较浅,今天被个小问题卡住了一上午了

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    list1 = ['CAT2', 'CAT1', 'DOG1', 'DOG2', 'FISH2', 'FISH1']
    
    def func (k):
        if k.find('FISH') != 1:
            return '1%s' % k
        elif k.find('CAT') != 1:
            return '2%s' % k
        return '3%s' % k
    
    print sorted(list1, key=func)
    

    得到的结果是['CAT1', 'CAT2', 'DOG1', 'DOG2', 'FISH1', 'FISH2'], 求教为什么不是['FISH1', 'FISH2', 'CAT1', 'CAT2', 'DOG1', 'DOG2']?

    4 条回复    2016-10-02 19:05:42 +08:00
    dreamtrail
        1
    dreamtrail  
    OP
       2016-10-02 11:18:24 +08:00
    原来是把-1 写成 1 。。。 V2EX 的帖子不能编辑么。。。
    zjuhwc
        2
    zjuhwc  
       2016-10-02 11:18:39 +08:00
    In [12]: 'FISH1'.find('FISH')
    Out[12]: 0

    In [13]: 'somestringFISH'.find('FISH')
    Out[13]: 10

    In [14]: 'CAT'.find('FISH')
    Out[14]: -1

    find 的效果是找到了就返回 index ,找不到就返回-1 ,在你这个用例里全都满足 != 1 所以加了等于没加。

    看起来你是想判断 FISH 是否在 k 里? 用 if 'FISH' in k 这样的语句
    dreamtrail
        3
    dreamtrail  
    OP
       2016-10-02 11:22:54 +08:00
    @zjuhwc
    谢谢,原来 in 还能这么用,学习了,的确如果用 in 就不会犯这种低级错误。。
    v3standup
        4
    v3standup  
       2016-10-02 19:05:42 +08:00
    @dreamtrail 先事欲明,先构思,复为,则无或曰罕之犯其小者矣
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   944 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 20:57 · PVG 04:57 · LAX 13:57 · JFK 16:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.