【问题标题】:map() with partial arguments: save up space带有部分参数的 map():节省空间
【发布时间】:2021-03-08 03:39:06
【问题描述】:

我有一个非常大的字典列表,其中键是(stringfloatstring)的三倍,其值又是列表。 cols_to_aggr 基本上是list(defaultdict(list))

我希望我不仅可以将列表索引i 传递给我的函数_compute_aggregation,而且还可以只传递该索引包含的数据,即cols_to_aggr[i],而不是整个数据结构cols_to_aggr,并且必须获得我的并行函数中的小块。 这是因为问题是整个数据结构的这种传递导致我的池完全没有效率地耗尽了我所有的内存。

with multiprocessing.Pool(processes=n_workers, maxtasksperchild=500) as pool:
    results = pool.map(
        partial(_compute_aggregation, cols_to_aggr=cols_to_aggr,
                aggregations=aggregations, pivot_ladetag_pos=pivot_ladetag_pos,
                to_ix=to_ix), cols_to_aggr)

def _compute_aggregation(index, cols_to_aggr, aggregations, pivot_ladetag_pos, to_ix):
    data_to_process = cols_to_aggr[index]

为了解决我的内存问题,我尝试设置maxtasksperchild,但没有成功,我不知道如何以最佳方式设置它。

【问题讨论】:

    标签: python python-3.x functional-programming python-multiprocessing


    【解决方案1】:

    使用dict.values(),您可以遍历字典的值。

    因此您可以将代码更改为:

    with multiprocessing.Pool(processes=n_workers, maxtasksperchild=500) as pool:
        results = pool.map(
            partial(_compute_aggregation,
                    aggregations=aggregations, pivot_ladetag_pos=pivot_ladetag_pos,
                    to_ix=to_ix), cols_to_aggr.values())
    
    def _compute_aggregation(value, aggregations, pivot_ladetag_pos, to_ix):
        data_to_process = value
    

    如果您仍需要 _compute_aggregation 函数中的密钥,请改用 dict.items()

    【讨论】:

    • 嗨@pypae,谢谢你的回答。我对一件事感到困惑:cols_to_aggr 是一个像 list(defaultdict(list)) 这样的对象 - 所以我不能直接将 dict 方法应用于它,不是吗?你提到如果我有defaultdict(list) 我可以做到这一点还是我错了?
    • 没错,我错了,抱歉。但是如果cols_to_aggrdefaultdict 的列表,那么index 应该已经是defaultdict 了吧?
    • 没错,但实际上你甚至更早地给了我一个想法,我摆脱了第一个list 表面并适应了:) 谢谢!您可以通过在 list 的情况下还包括 index 来更新您的答案,这样如果有人路过就不会被误导:)
    猜你喜欢
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 2020-09-25
    • 2011-01-28
    相关资源
    最近更新 更多