python同时追加和读取列表

2024-04-28 02:59:51 发布

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

我的情况是,我必须同时读和写清单。 似乎代码在完成对名单。什么我想做的是,代码将继续在一端添加元素,我需要继续同时处理前10个元素。你知道吗

import csv

testlist=[]
with open('some.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
         testlist.append(row)



def render(small)
   #do some stuff



while(len(testlist)>0)
      pool = Pool(processes=10)
      small=testlist[:10]
      del testlist[:10]
      pool.map_async(render,small)
      pool.close()
      pool.join()

Tags: csv代码import元素with情况someopen
2条回答

你可以这样做

x=[]
y=[1,2,3,4,5,6,7,...]
for i in y:
    x.append(i)
    if len(x)<10:
       print x
    else:
        print x[:10]
        x=x-x[:10]

PS:假设y是无限流

您需要一个在进程之间共享的队列。一个进程添加到队列中,另一个进程从队列中删除。你知道吗

下面是一个简化的示例:

from multiprocessing import Process, Queue

def put(queue):
   # writes items to the queue
   queue.put('something')

def get(queue):
   # gets item from the queue to work on
   while True:
     item = queue.get()
     # do something with item

if __name__=='__main__':
    queue = Queue()
    getter_process = Process(target=get, args=((queue),))
    getter_process.daemon = True
    getter_process.start()
    writer(queue)          # Send something to the queue  
    getter_process.join()  # Wait for the getter to finish

如果一次只处理10件事情,可以将队列大小限制为10。这意味着,“writer”不能写任何东西,除非队列已经有10个项目等待处理。你知道吗

默认情况下,队列没有边界/限制。documentation是一个开始了解更多队列的好地方。你知道吗

相关问题 更多 >