【发布时间】:2013-08-25 20:41:27
【问题描述】:
我正在尝试在 Python3 中使用 map。这是我正在使用的一些代码:
import csv
data = [
[1],
[2],
[3]
]
with open("output.csv", "w") as f:
writer = csv.writer(f)
map(writer.writerow, data)
但是,由于 Python3 中的 map 返回一个迭代器,因此该代码在 Python3 中不起作用(但在 Python2 中可以正常工作,因为该版本的 map 总是返回 list)
我目前的解决方案是在迭代器上添加一个list 函数调用以强制评估。但这似乎很奇怪(我不关心返回值,为什么要将迭代器转换为列表?)
有更好的解决方案吗?
【问题讨论】:
-
使用
map获得副作用是很奇怪的。 Python 2map也收集返回值。新行为只是进一步突出了它。不要那样做,use a for loop。 -
@delnan 谢谢你的链接,确实我不应该使用
map来获得副作用。 -
对于 Python 3,
list(map(lambda x:2*x, [1,2,3]))
标签: python