map在python 3中无法正常工作

Win*_*Man 4 python functional-programming

新手在这里.

这段代码在python 2.7中有效,但在3.3中没有

def extractFromZipFiles(zipFiles, files, toPath):
    extractFunction = lambda fileName:zipFiles.extract(fileName, toPath) 
    map (extractFunction,files)
    return
Run Code Online (Sandbox Code Playgroud)

没有错误,但文件未被提取.但是,当我用for循环替换工作正常.

def extractFromZipFiles(zipFiles, files, toPath):
    for fn in files:
        zipFiles.extract(fn, toPath)
#     extractFunction = lambda fileName:zipFiles.extract(fileName, toPath) 
#     map (extractFunction,files)
    return
Run Code Online (Sandbox Code Playgroud)

代码没有错误.

mhl*_*ter 8

通常不鼓励使用map来调用函数,但是说,它不起作用的原因是因为Python 3返回一个生成器,而不是一个列表,所以在你迭代它之前不会调用该函数.确保它调用函数:

list(map(extractFunction,files))
Run Code Online (Sandbox Code Playgroud)

但它正在创建一个未使用的列表.更好的方法是更明确:

for file in files:
    extractFunction(file)
Run Code Online (Sandbox Code Playgroud)

与头部的情况一样,两条线确实可以比一条线好.