python 字典处理的一些坑_Python多处理字典中的每个键

I am new to python and i am trying to scale my processing in parallel. I have a file with certain number of tuples, each with certain value in the last column. I want to split this file data and apply my function in parallel to each chunk. But the thing is to split the data in to chunks based on last column value and apply the function for each chunk. For example, last column may have 'a' for some tuples and 'b' for some and 'c' for some. So in that case, i should get three chunks and process it in parallel. Number of unique values in last column may change depends on dataset, so i need to use the CPU accordingly.

Q1:

What i tried till now is to read the file and created a dictionary based on that records, so basically three key-value pairs for the above one, one with 'a' as key and all records having 'a' as values and the same to 'b' and 'c'. I can make use of chunksize in multiprocessing, but here it is not size, its based on key, so how can i achieve this?

Q2:

After processing the above chunks, i need the output of all together,order does not matter and then i need to use the whole output for further processing, how can i make my main program wait till all those process complete?

Let me know if further input is required. Thanks.

解决方案

Assuming, as you described, you have a three sets as values on dictionary d, and want to apply function f to each of them separately:

from multiprocessing import Pool

p = Pool() #number of processes = number of CPUs

keys, values= zip(*d.iteritems()) #ordered keys and values

processed_values= p.map( f, values ) #apply the function f to each set and wait for result

#then proceed to join the three sets

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值