Cof*_*fyc 5 python functional-programming python-3.x
我使用lambda编写了一行代码来关闭python2.6中的文件对象列表:
map(lambda f: f.close(), files)
Run Code Online (Sandbox Code Playgroud)
它可以工作,但不在python3.1中.为什么?
这是我的测试代码:
import sys
files = [sys.stdin, sys.stderr]
for f in files: print(f.closed) # False in 2.6 & 3.1
map(lambda o : o.close(), files)
for f in files: print(f.closed) # True in 2.6 but False in 3.1
for f in files: f.close()
for f in files: print(f.closed) # True in 2.6 & 3.1
Run Code Online (Sandbox Code Playgroud)
map 在Python 2中返回一个列表,但在Python 3中返回一个迭代器.因此,只有在迭代结果时才会关闭文件.
从不map对具有副作用的功能应用或类似的"功能"功能.Python不是一种功能语言,永远不会.使用for循环:
for o in files:
o.close()
Run Code Online (Sandbox Code Playgroud)