您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python关闭无法正常工作

Python关闭无法正常工作

一种方法是执行此操作:

def main():
    files = [r'C:\_local\test.txt', r'C:\_local\junk.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 partial
for f in files:
    # create a partially applied function
    funcs.append(partial(os.stat, f))
python 2022/1/1 18:29:14 有183人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶