gpt4 book ai didi

Python 3.6 - 使用异步函数进行过滤

转载 作者:行者123 更新时间:2023-12-03 08:53:39 26 4
gpt4 key购买 nike

这是一个非常基本的问题,但找不到相关的详细信息。

当我想用来过滤元素的函数是异步的时,如何使用内置的过滤函数?

示例:

import asyncio


async def not_one(item):
if item == 1:
await asyncio.sleep(1) # Just to give an asyc feel..
return False
return True


async def main():
org_list = [1, 2, 3]

# IMPLEMENTATION #1 - WITHOUT USING FILTER
without_one_list = []
for item in org_list:
is_one = await not_one(item)
if is_one:
without_one_list.append(item)

print(without_one_list) # [2, 3]

# NOT WORKING #1 - not_one was never awaited
without_one_list = list(filter(not_one, org_list))

# NOT WORKING #2 - not a valid syntax
without_one_list = list(filter(await not_one, org_list))

# NOT WORKING #3 - not a valid syntax
without_one_list = list(await filter(not_one, org_list))


if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

如何在使用过滤功能时做我想做的事?

谢谢

最佳答案

在Python 3.6中你可以使用Asynchronous Generators

您应该能够自己定义一个简单的async_filter,如下所示:

async def async_filter(async_pred, iterable):
for item in iterable:
should_yield = await async_pred(item)
if should_yield:
yield item

那么你可以使用 Asynchronous Comprehensions 来获取列表:

import asyncio


async def not_one(item):
if item == 1:
await asyncio.sleep(1) # Just to give an asyc feel..
return False
return True

async def async_filter(async_pred, iterable):
for item in iterable:
should_yield = await async_pred(item)
if should_yield:
yield item


async def main():
org_list = [1, 2, 3]

# IMPLEMENTATION #1 - WITHOUT USING FILTER
without_one_list = []
for item in org_list:
is_one = await not_one(item)
if is_one:
without_one_list.append(item)

print(without_one_list) # [2, 3]

without_one_list_async = [i async for i in async_filter(not_one, org_list)]
print(without_one_list_async)
print(without_one_list_async == without_one_list)


if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

输出:

[2, 3]
[2, 3]
True

关于Python 3.6 - 使用异步函数进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57285478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com