推荐学习书目
› 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 · Oct 2, 2016 · 4074 views
    This topic created in 3658 days ago, the information mentioned may be changed or developed.

    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 replies  •  2016-10-02 19:05:42 +08:00
    dreamtrail
        1
    dreamtrail  
    OP
       Oct 2, 2016
    原来是把-1 写成 1 。。。 V2EX 的帖子不能编辑么。。。
    zjuhwc
        2
    zjuhwc  
       Oct 2, 2016
    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
       Oct 2, 2016
    @zjuhwc
    谢谢,原来 in 还能这么用,学习了,的确如果用 in 就不会犯这种低级错误。。
    v3standup
        4
    v3standup  
       Oct 2, 2016
    @dreamtrail 先事欲明,先构思,复为,则无或曰罕之犯其小者矣
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5727 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 07:13 · PVG 15:13 · LAX 00:13 · JFK 03:13
    ♥ Do have faith in what you're doing.