検索

An Alternating Asynchronous Generator in Python

from asyncio import run, sleep

class AlternatingGenerator:
    def __init__(self, gen1, gen2):
        self.gen1 = gen1
        self.gen2 = gen2
        self.next = gen1

    def __aiter__(self):
        return self

    async def __anext__(self):

        # if we are done we both generators
        if not self.gen1 and not self.gen2:
            raise StopAsyncIteration

        try:
            # saving the current generator into a variable for later
            current = self.next

            # if the other genrerator is not null, alternating to it for the next iteration
            if self.next is self.gen1 and self.gen2:
                self.next = self.gen2
            elif self.next is self.gen2 and self.gen1:
                self.next = self.gen1

            # calling the generator of the current iteration and returning the next result
            return await anext(current)

        except StopAsyncIteration:

            # unsetting the generator that just finished
            if current is self.gen1:
                self.gen1 = None
            else:
                self.gen2 = None

            # recursive call, trying again with the other generator
            return await self.__anext__()



async def three():
    for i in range(3, 31, 10):
        await sleep(0.25)
        yield i


async def five():
    for i in range(5, 101, 10):
        await sleep(0.25)
        yield i

async def main():
    gen = AlternatingGenerator(three(), five())

    try:  # or just use "async for item in gen:"
        while True:
            print(await anext(gen))
    except StopAsyncIteration:
        pass

if __name__ == '__main__':
    run(main())
$ python alternating_generator.py 
3
5
13
15
23
25
35
45
55
65
75
85
95

以上がPython の代替非同期ジェネレーターの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Pythonリストをどのようにスライスしますか?Pythonリストをどのようにスライスしますか?May 02, 2025 am 12:14 AM

slicingapythonlistisdoneusingtheyntaxlist [start:stop:step] .hore'showitworks:1)startisthe indexofthefirstelementtoinclude.2)spotisthe indexofthefirmenttoeexclude.3)staptistheincrementbetbetinelements

Numpyアレイで実行できる一般的な操作は何ですか?Numpyアレイで実行できる一般的な操作は何ですか?May 02, 2025 am 12:09 AM

numpyallows forvariousoperationsonarrays:1)basicarithmeticlikeaddition、減算、乗算、および分割; 2)AdvancedperationssuchasmatrixMultiplication;

Pythonを使用したデータ分析では、配列はどのように使用されていますか?Pythonを使用したデータ分析では、配列はどのように使用されていますか?May 02, 2025 am 12:09 AM

Arraysinpython、特にnumpyandpandas、aresentialfordataanalysis、offeringspeedandeficiency.1)numpyarraysenable numpyarraysenable handling forlaredatasents andcomplexoperationslikemoverages.2)Pandasextendsnumpy'scapabivitieswithdataframesfortruc

リストのメモリフットプリントは、Pythonの配列のメモリフットプリントとどのように比較されますか?リストのメモリフットプリントは、Pythonの配列のメモリフットプリントとどのように比較されますか?May 02, 2025 am 12:08 AM

listsandnumpyarraysinpythonhavedifferentmemoryfootprints:listsaremoreflexiblellessmemory-efficient、whileenumpyarraysaraysareoptimizedfornumericaldata.1)listsstorereferencesto objects、with whowedaround64byteson64-bitedatigu

実行可能なPythonスクリプトを展開するとき、環境固有の構成をどのように処理しますか?実行可能なPythonスクリプトを展開するとき、環境固有の構成をどのように処理しますか?May 02, 2025 am 12:07 AM

toensurepythonscriptsbehaveCorrectlyAcrossDevelosment、staging、and Production、usetheseStrategies:1)環境variablesforsimplestetings、2)configurationfilesforcomplexsetups、and3)dynamicloadingforadaptability.eachtododododododofersuniquebentandrequiresca

Pythonアレイをどのようにスライスしますか?Pythonアレイをどのようにスライスしますか?May 01, 2025 am 12:18 AM

Pythonリストスライスの基本的な構文はリストです[start:stop:step]。 1.STARTは最初の要素インデックス、2。ストップは除外された最初の要素インデックスであり、3.ステップは要素間のステップサイズを決定します。スライスは、データを抽出するためだけでなく、リストを変更および反転させるためにも使用されます。

どのような状況で、リストは配列よりもパフォーマンスが向上しますか?どのような状況で、リストは配列よりもパフォーマンスが向上しますか?May 01, 2025 am 12:06 AM

ListSoutPerformArraysIn:1)ダイナミシジョンアンドフレーケンティオン/削除、2)ストーリングヘテロゼンダタ、および3)メモリ効率の装飾、ButmayhaveslightPerformancostsinceNASOPERATIONS。

PythonアレイをPythonリストに変換するにはどうすればよいですか?PythonアレイをPythonリストに変換するにはどうすればよいですか?May 01, 2025 am 12:05 AM

toconvertapythonarraytoalist、usetheList()constructororageneratorexpression.1)importhearraymoduleandcreateanarray.2)useList(arr)または[xforxinarr] toconvertoalistは、largedatatessを変えることを伴うものです。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

WebStorm Mac版

WebStorm Mac版

便利なJavaScript開発ツール