一种方法是执行此 *** 作:
def main(): files = [r'C:_localtest.txt', r'C:_localjunk.txt'] funcs = [] for f in files: # create a new lambda and store the current `f` as default to `path` funcs.append(lambda path=f: os.stat(path)) print funcs # calling the lambda without a parameter uses the default value funcs[0]() funcs[1]()
否则
f,在调用该函数时将进行查找,因此您将获得当前(循环后)的值。
我更喜欢的方式:
def make_statfunc(f): return lambda: os.stat(f)for f in files: # pass the current f to another function funcs.append(make_statfunc(f))
甚至(在python 2.5+中):
from functools import partialfor f in files: # create a partially applied function funcs.append(partial(os.stat, f))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)