地图无法在python 3中按预期方式工作 [英] map doesn't work as expected in python 3
问题描述
新手在这里.
此代码在python 2.7中有效,但在3.3中无效
This code worked in python 2.7, but does not in 3.3
def extractFromZipFiles(zipFiles, files, toPath):
extractFunction = lambda fileName:zipFiles.extract(fileName, toPath)
map (extractFunction,files)
return
没有错误,但未提取文件.但是,当我用for循环替换时,效果很好.
No error but the files are not extracted. However when I replace with for loop works fine.
def extractFromZipFiles(zipFiles, files, toPath):
for fn in files:
zipFiles.extract(fn, toPath)
# extractFunction = lambda fileName:zipFiles.extract(fileName, toPath)
# map (extractFunction,files)
return
代码没有错误.
推荐答案
通常不鼓励使用map来调用函数,但是,不起作用的原因是因为Python 3返回了一个生成器,而不是列表,因此在您对其进行迭代之前,不会调用该函数.为了确保它调用这些函数,请执行以下操作:
It is generally discouraged to use map to call functions, but that being said, the reason it doesn't work is because Python 3 returns a generator, not a list, so the function isn't called until you've iterated on it. To ensure that it calls the functions:
list(map(extractFunction,files))
但是它正在创建一个未使用的列表.更好的方法是更明确:
But it's creating an unused list. The better approach is to be more explicit:
for file in files:
extractFunction(file)
就像有头的情况一样,两行确实可以胜过一行.
As is the case with heads, two lines can indeed be better than one.
这篇关于地图无法在python 3中按预期方式工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!