Python 带变量的 lambda 函数的 AsyncHTMLSession 不起作用
Python AsyncHTMLSession with lambda function with variable not work
下面的代码得到4,4,4,4,4
预计0,1,2,3,4
它适用于 functools.partial 但不适用于 lambda,如何解决?
from requests_html import AsyncHTMLSession
asession = AsyncHTMLSession()
async def download(index):
print(index)
def main():
lst = []
for index in range(5):
lst.append(lambda: download(index))
asession.run(*lst)
if __name__ == "__main__":
main()
您需要像这样将索引传递给您的 lambda:lambda index=index: download(index)
def main():
lst = []
for index in range(5):
lst.append(lambda: download(index))
# Here when you run your lambda the index variable is in
# the main function scope, so the value is 4 for all the lambda
# because the loop is ended.
asession.run(*lst)
def main():
lst = []
for index in range(5):
lst.append(lambda foo=index: download(foo))
# Here a new variable foo is created in the scope of the lambda
# with the value of index for each iteration of the loop
asession.run(*lst)
有关详细信息,已记录 here !
下面的代码得到4,4,4,4,4
预计0,1,2,3,4
它适用于 functools.partial 但不适用于 lambda,如何解决?
from requests_html import AsyncHTMLSession
asession = AsyncHTMLSession()
async def download(index):
print(index)
def main():
lst = []
for index in range(5):
lst.append(lambda: download(index))
asession.run(*lst)
if __name__ == "__main__":
main()
您需要像这样将索引传递给您的 lambda:lambda index=index: download(index)
def main():
lst = []
for index in range(5):
lst.append(lambda: download(index))
# Here when you run your lambda the index variable is in
# the main function scope, so the value is 4 for all the lambda
# because the loop is ended.
asession.run(*lst)
def main():
lst = []
for index in range(5):
lst.append(lambda foo=index: download(foo))
# Here a new variable foo is created in the scope of the lambda
# with the value of index for each iteration of the loop
asession.run(*lst)
有关详细信息,已记录 here !