
平时写 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)) 当然我可以把要做的操作定义成方法,不过方法多了也比较麻烦。
请问最优雅的做法是什么?
1 binux 2016-11-29 03:47:27 +08:00 for row in table: for cell in row: do_something(cell) |
2 lightening OP @binux 我要不改动原 table 的情况下新建一个 table ,这样的话就要不停地手动建立元素然后插入新列表 |
3 binux 2016-11-29 03:56:09 +08:00 @lightening 那你就在 do_something 里面写多几行不就行了 |
4 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] |
5 wellsc 2016-11-29 09:27:54 +08:00 via Android 用 map |
6 zmrenwu 2016-11-29 09:41:43 +08:00 import pandas as pd |
7 wwulfric 2016-11-29 10:43:06 +08:00 同 4L , Python 的 lambda 比较费,只能提前建好一个函数了 |
8 hanbaobao2005 2016-11-29 11:10:26 +08:00 不建议使用: [[do_something(cell) for cell in row] for row in table] 这种写法,有坑。 |
9 hanbaobao2005 2016-11-29 11:19:45 +08:00 哦。我也想把具体的 “坑” 说清楚,但时间太久了。 Orz... |
10 woostundy 2016-11-29 15:35:09 +08:00 map(lambda x:map(do_something,x),a) |