How do I parallelize a simple Python loop?

后端 未结 13 1575
北荒
北荒 2020-11-22 11:54

This is probably a trivial question, but how do I parallelize the following loop in python?

# setup output lists
output1 = list()
output2 = list()
output3 =          


        
13条回答
  •  清歌不尽
    2020-11-22 12:29

    Let's say we have an async function

    async def work_async(self, student_name: str, code: str, loop):
    """
    Some async function
    """
        # Do some async procesing    
    

    That needs to be run on a large array. Some attributes are being passed to the program and some are used from property of dictionary element in the array.

    async def process_students(self, student_name: str, loop):
        market = sys.argv[2]
        subjects = [...] #Some large array
        batchsize = 5
        for i in range(0, len(subjects), batchsize):
            batch = subjects[i:i+batchsize]
            await asyncio.gather(*(self.work_async(student_name,
                                               sub['Code'],
                                               loop)
                           for sub in batch))
    

提交回复
热议问题