Newbie here.
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
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
Code doesn't error.
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.
map
in python3 is an iterator, whereas in python2, it computed a list. So, what you're looking for, is a way to consume the entire iterator . Thankfully, there's an itertools
recipe for this:
import collections
def extractFromZipFiles(zipFiles, files, toPath):
extractFunction = lambda fileName:zipFiles.extract(fileName, toPath)
collections.deque(map(extractFunction,files), maxlen=0)
return
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.