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

关于 list 中按字符串长度排序的问题

  •  
  •   omg21 · Apr 13, 2016 · 4088 views
    This topic created in 3693 days ago, the information mentioned may be changed or developed.
    lista = ['s','app','77822','id']
    lista.sort(key=len) #这句是把 lista 按字符串长度排序成这样[‘ s ’,'id','app','77822']

    lista = [(0,'s'),(1,'app'),(2,'77822'),(3,'id')]
    #现在是列表数组,仍然按第二列的字符串长度排序怎么做?
    12 replies    2016-04-14 11:38:54 +08:00
    SoloCompany
        1
    SoloCompany  
       Apr 13, 2016   ❤️ 1
    lista.sort(key=lambda x:len(x[1]))
    omg21
        2
    omg21  
    OP
       Apr 14, 2016
    谢谢,通过了,能解释下吗?你这句我看不懂。
    @SoloCompany
    SoloCompany
        3
    SoloCompany  
       Apr 14, 2016
    @omg21 key 参数是一个函数指针,指向的是一个匿名函数,定义为 f(x) -> { return len(x[1]) }
    lambda 关键字是 python 用来定义匿名函数的,有点累赘但他们喜欢这样
    omg21
        4
    omg21  
    OP
       Apr 14, 2016
    还有,现在 lista 中是[(0,'s'),(3,'id'),(1,'app'),(2,'77822')]
    那么我现在想取出长度第二的(3,'id')中的 3 应该怎么写?
    omg21
        5
    omg21  
    OP
       Apr 14, 2016
    SoloCompany
        6
    SoloCompany  
       Apr 14, 2016
    。。。这难道不是基础到不能再基础吗 lista[1][0]
    knightdf
        7
    knightdf  
       Apr 14, 2016
    @omg21 sorted([(0,'s'),(3,'id'),(1,'app'),(2,'77822')], key=lambda x: len(x[1]))[1][0]
    omg21
        8
    omg21  
    OP
       Apr 14, 2016
    @knightdf 不好意思,刚才晕头了,用 print(list_a_text[1,0])取的,正好看见你在,又连忙问下
    Abirdcfly
        9
    Abirdcfly  
       Apr 14, 2016
    @SoloCompany 唔.我有点迷糊了..为什么 lambda x:len(x[1]) x 会=lista.items 呢?(没有这个方法..就是这个意思)?
    SoloCompany
        10
    SoloCompany  
       Apr 14, 2016
    @Abirdcfly 我建议你先了解一下 fp 的基础知识
    https://zh.wikipedia.org/wiki/%E5%87%BD%E6%95%B8%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80
    当然,中文 wiki 上是没多少内容的,但英文的则是 TLDR 要不要看就自己决定吧
    darkbread
        11
    darkbread  
       Apr 14, 2016
    都说 Python 应该作为入门语言,这不,问题来了.
    noble4cc
        12
    noble4cc  
       Apr 14, 2016
    使用 lambda 表达式,上边有人说过了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   891 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 22:18 · PVG 06:18 · LAX 15:18 · JFK 18:18
    ♥ Do have faith in what you're doing.