在此函数中实现多线程的最简单方法[Python]

2024-04-25 19:32:02 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个名为id_list的数据,它以这种格式进入函数[(u'SGP-3630', 1202), (u'MTSCR-534', 1244)]。如果格式是两个值配对在一起,则可能有1对或100对。你知道吗

这是函数:

def ListParser(id_list):
    list_length = len(id_list)
    count = 0
    table = ""

    while count < list_length:
        jira = id_list[count][0]
        stash = id_list[count][1]
        count = count + 1
        table = table + RetrieveFromAPI(stash, jira)

    table = TableFormatter(table)
    table = TableColouriser(table)

    return table

这个函数所做的是遍历列表,提取成对的内容,并通过一个名为RetrieveFromAPI()的函数将它们放入其中,该函数从URL获取信息。你知道吗

有人知道如何在这里实现多线程吗?我曾尝试过将两个列表拆分为各自的列表,并让池遍历每个列表,但效果并不理想。你知道吗

def ListParser(id_list):
    pool = ThreadPool(4)
    list_length = len(id_list)
    count = 0
    table = ""
    jira_list = list()
    stash_list = list()

    while count < list_length:
        jira_list = jira_list.extend(id_list[count][0])
        print jira_list
        stash_list = stash_list.extend(id_list[count][1])
        print stash_list
        count = count + 1

    table = table + pool.map(RetrieveFromAPI, stash_list, jira_list)
    table = TableFormatter(table)
    table = TableColouriser(table)

    return table

我这次尝试的错误是TypeError: 'int' object is not iterable

编辑2:好的,我已经设法得到第一个元组被分成两个不同列表的列表,但是我不确定如何使用多线程处理它。你知道吗

jira,stash= map(list,zip(*id_list))


Tags: 函数id列表lendef格式counttable
1条回答
网友
1楼 · 发布于 2024-04-25 19:32:02

你工作太辛苦了!从help(multiprocessing.pool.ThreadPool)

map(self, func, iterable, chunksize=None)
    Apply `func` to each element in `iterable`, collecting the results
    in a list that is returned.

第二个参数是要传递给工作线程的参数的iteable。您有一个列表列表,并且希望每个呼叫的前两项都来自内部列表。id_list已经是iterable了,所以我们很接近了。一个小函数(在本例中实现为lambda)弥补了这一差距。你知道吗

我设计了一个完整的模拟解决方案,只是为了确保它能正常工作。另一方面,您可以受益于相当大的池大小,因为它们将大部分时间用于等待I/O

from multiprocessing.pool import ThreadPool

def RetrieveFromAPI(stash, jira):
    # boring mock of api
    return '{}-{}.'.format(stash, jira)

def TableFormatter(table):
    # mock
    return table

def TableColouriser(table):
    # mock
    return table

def ListParser(id_list):
    if id_list:
        pool = ThreadPool(min(12, len(id_list)))
        table = ''.join(pool.map(lambda item: RetrieveFromAPI(item[1], item[0]),
            id_list, chunksize=1))
        pool.close()
        pool.join()
    else:
        table = ''
    table = TableFormatter(table)
    table = TableColouriser(table)
    return table

id_list = [[0,1,'foo'], [2,3,'bar'], [4,5, 'baz']]

print(ListParser(id_list))

相关问题 更多 >