【发布时间】:2013-01-26 11:30:50
【问题描述】:
我正在编写一个函数来随机选择存储在字典中的元素:
import random
from liblas import file as lasfile
from collections import defaultdict
def point_random_selection(list,k):
try:
sample_point = random.sample(list,k)
except ValueError:
sample_point = list
return(sample_point)
def world2Pixel_Id(x,y,X_Min,Y_Max,xDist,yDist):
col = int((x - X_Min)/xDist)
row = int((Y_Max - y)/yDist)
return("{0}_{1}".format(col,row))
def point_GridGroups(inFile,X_Min,Y_Max,xDist,yDist):
Groups = defaultdict(list)
for p in lasfile.File(inFile,None,'r'):
id = world2Pixel_Id(p.x,p.y,X_Min,Y_Max,xDist,yDist)
Groups[id].append(p)
return(Groups)
其中 k 是要选择的元素的数量。组就是字典
file_out = lasfile.File("outPut",mode='w',header= h)
for m in Groups.iteritems():
# select k point for each dictionary key
point_selected = point_random_selection(m[1],k)
for l in xrange(len(point_selected)):
# save the data
file_out.write(point_selected[l])
file_out.close()
我的问题是这种方法非常慢(大约 4 天左右的文件约为 800 Mb)
【问题讨论】:
-
random.sample()速度已经过优化,但如果你向它投入非常大的输入,你就会遇到不同的问题。Groups中有什么内容?Groups是否填充了 800 MB 文件中的数据点? -
亲爱的 Martijn 是的,Gropus 填充了 800 MB 文件中的数据点。如果 liblas 在 C++ 中,也可能瓶颈是 file_out.write(point_selected[l])
-
你生成了多少数据,你在写什么到等等。你是否分析了你的代码并确定它是
random.sample()在这里很慢或者你只是猜? -
有一些方法可以从文件中随机抽取行样本,而无需将整个文件读入内存。见Python random N lines from large file (no duplicate lines) 和Python random lines from subfolders
-
问题是我需要读取点文件 (x,y) 给出网格内空间位置函数的 ID(例如:1 mx 1 m)并随机提取一个点(o更多)对于每个网格。出于这个原因,我需要在整个点文件之前阅读。
标签: python performance optimization random dictionary