簡體   English   中英

地圖在 python 3 中無法按預期工作

[英]map doesn't work as expected in python 3

新手來了

此代碼在 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)

與頭部的情況一樣,兩條線確實比一條好。

python3 中的map是一個迭代器,而在 python2 中,它計算一個列表。 所以,您正在尋找的是一種使用整個 iterator 的方法 值得慶幸的是,有一個itertools食譜

import collections
def extractFromZipFiles(zipFiles, files, toPath):
    extractFunction = lambda fileName:zipFiles.extract(fileName, toPath) 
    collections.deque(map(extractFunction,files), maxlen=0)
    return

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM