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

2016-11-29 03:33:57 +08:00
 lightening

平时写 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))

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

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

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

def do_something(cell):
____pass

[[do_something(cell) for cell in row] for row in table]
wellsc
2016-11-29 09:27:54 +08:00
用 map
zmrenwu
2016-11-29 09:41:43 +08:00
import pandas as pd
wwulfric
2016-11-29 10:43:06 +08:00
同 4L , Python 的 lambda 比较费,只能提前建好一个函数了
hanbaobao2005
2016-11-29 11:10:26 +08:00
不建议使用:
[[do_something(cell) for cell in row] for row in table]
这种写法,有坑。
hanbaobao2005
2016-11-29 11:19:45 +08:00
哦。我也想把具体的 “坑” 说清楚,但时间太久了。 Orz...
woostundy
2016-11-29 15:35:09 +08:00
map(lambda x:map(do_something,x),a)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/323996

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX