gpt4 book ai didi

python - map 在 python 3 中无法正常工作

转载 作者:太空狗 更新时间:2023-10-30 02:11:34 26 4
gpt4 key购买 nike

这里是新手。

此代码在 python 2.7 中有效,但在 3.3 中无效

def extractFromZipFiles(zipFiles, files, toPath):
extractFunction = lambda fileName:zipFiles.extract(fileName, toPath)
map (extractFunction,files)
return

没有错误,但没有提取文件。但是,当我用 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

代码没有错误。

最佳答案

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

list(map(extractFunction,files))

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

for file in files:
extractFunction(file)

就像头像一样,两行确实比一行好。

关于python - map 在 python 3 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21540653/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com