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

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

  •  
  •   omg21 · 2016-04-13 22:59:19 +08:00 · 3529 次点击
    这是一个创建于 2943 天前的主题,其中的信息可能已经有所发展或是发生改变。
    lista = ['s','app','77822','id']
    lista.sort(key=len) #这句是把 lista 按字符串长度排序成这样[‘ s ’,'id','app','77822']

    lista = [(0,'s'),(1,'app'),(2,'77822'),(3,'id')]
    #现在是列表数组,仍然按第二列的字符串长度排序怎么做?
    12 条回复    2016-04-14 11:38:54 +08:00
    SoloCompany
        1
    SoloCompany  
       2016-04-13 23:45:32 +08:00   ❤️ 1
    lista.sort(key=lambda x:len(x[1]))
    omg21
        2
    omg21  
    OP
       2016-04-14 00:08:34 +08:00
    谢谢,通过了,能解释下吗?你这句我看不懂。
    @SoloCompany
    SoloCompany
        3
    SoloCompany  
       2016-04-14 00:16:36 +08:00
    @omg21 key 参数是一个函数指针,指向的是一个匿名函数,定义为 f(x) -> { return len(x[1]) }
    lambda 关键字是 python 用来定义匿名函数的,有点累赘但他们喜欢这样
    omg21
        4
    omg21  
    OP
       2016-04-14 00:17:50 +08:00
    还有,现在 lista 中是[(0,'s'),(3,'id'),(1,'app'),(2,'77822')]
    那么我现在想取出长度第二的(3,'id')中的 3 应该怎么写?
    omg21
        5
    omg21  
    OP
       2016-04-14 00:18:19 +08:00
    SoloCompany
        6
    SoloCompany  
       2016-04-14 00:20:29 +08:00
    。。。这难道不是基础到不能再基础吗 lista[1][0]
    knightdf
        7
    knightdf  
       2016-04-14 00:22:25 +08:00
    @omg21 sorted([(0,'s'),(3,'id'),(1,'app'),(2,'77822')], key=lambda x: len(x[1]))[1][0]
    omg21
        8
    omg21  
    OP
       2016-04-14 00:26:44 +08:00
    @knightdf 不好意思,刚才晕头了,用 print(list_a_text[1,0])取的,正好看见你在,又连忙问下
    Abirdcfly
        9
    Abirdcfly  
       2016-04-14 01:07:53 +08:00
    @SoloCompany 唔.我有点迷糊了..为什么 lambda x:len(x[1]) x 会=lista.items 呢?(没有这个方法..就是这个意思)?
    SoloCompany
        10
    SoloCompany  
       2016-04-14 01:48:43 +08:00
    @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  
       2016-04-14 07:20:18 +08:00
    都说 Python 应该作为入门语言,这不,问题来了.
    noble4cc
        12
    noble4cc  
       2016-04-14 11:38:54 +08:00
    使用 lambda 表达式,上边有人说过了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1187 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 00:00 · PVG 08:00 · LAX 17:00 · JFK 20:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.