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

Python 中如何优雅地写多行列表解析?

  •  
  •   lightening ·
    SteveLTN · 2016-11-29 03:33:57 +08:00 · 5747 次点击
    这是一个创建于 2677 天前的主题,其中的信息可能已经有所发展或是发生改变。

    平时写 Ruby 比较多,最近要写些 Python 。比如我有一个表格,需要对每个单元格做一些操作,然后返回一个新表格,用 Ruby ,我会这样:

    # Ruby
    table.map { |row|
      row.map { |cell|
        ...
        do_something(cell)
        ...
      }
    }
    

    如果这个 do_something 逻辑需要多行,如何在 Python 中优雅的实现呢?

    试过:

    列表解析:

    [[do_something(cell) for cell in row] for row in table]
    
    

    但是我不知道如何优雅地扩展成多行。

    同样的,用 map 也难以扩展成多行:

    list(map(lambda row: list(map(lambda cell: do_something(cell), row)), table))
    

    当然我可以把要做的操作定义成方法,不过方法多了也比较麻烦。

    请问最优雅的做法是什么?

    10 条回复    2016-11-29 15:35:09 +08:00
    binux
        1
    binux  
       2016-11-29 03:47:27 +08:00
    for row in table:
    for cell in row:
    do_something(cell)
    lightening
        2
    lightening  
    OP
       2016-11-29 03:50:53 +08:00
    @binux 我要不改动原 table 的情况下新建一个 table ,这样的话就要不停地手动建立元素然后插入新列表
    binux
        3
    binux  
       2016-11-29 03:56:09 +08:00   ❤️ 1
    @lightening 那你就在 do_something 里面写多几行不就行了
    czheo
        4
    czheo  
       2016-11-29 05:39:16 +08:00   ❤️ 1
    Python 顶多就这样了。 lambda 只能单行,不比 ruby 的 block 灵活。

    def do_something(cell):
    ____pass

    [[do_something(cell) for cell in row] for row in table]
    wellsc
        5
    wellsc  
       2016-11-29 09:27:54 +08:00 via Android
    用 map
    zmrenwu
        6
    zmrenwu  
       2016-11-29 09:41:43 +08:00   ❤️ 1
    import pandas as pd
    wwulfric
        7
    wwulfric  
       2016-11-29 10:43:06 +08:00   ❤️ 1
    同 4L , Python 的 lambda 比较费,只能提前建好一个函数了
    hanbaobao2005
        8
    hanbaobao2005  
       2016-11-29 11:10:26 +08:00   ❤️ 1
    不建议使用:
    [[do_something(cell) for cell in row] for row in table]
    这种写法,有坑。
    hanbaobao2005
        9
    hanbaobao2005  
       2016-11-29 11:19:45 +08:00
    哦。我也想把具体的 “坑” 说清楚,但时间太久了。 Orz...
    woostundy
        10
    woostundy  
       2016-11-29 15:35:09 +08:00   ❤️ 1
    map(lambda x:map(do_something,x),a)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   985 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 22:10 · PVG 06:10 · LAX 15:10 · JFK 18:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.