[英]Speeding up Python iteration
我必須遍歷大約1.300.000行的列表。 時間順序很重要!
它的形狀如下:
Z X Y
18,139869,87718
18,139869,87719
18,139869,87722
18,139869,87725
18,139869,87726
18,139869,87751
18,139869,87752
18,139869,87841
18,139869,87842
18,139869,87843
18,139869,87844
18,139869,87845
18,139869,87846
18,139869,87847
18,139869,87861
18,139869,87862
18,139869,87882
18,139869,87886
18,139869,87887
18,139869,87888
18,139869,87889
18,139869,87890
18,139869,87891
18,139869,87902
18,139869,87912
18,139869,87913
18,139869,87914
18,139869,87918
18,139869,87919
18,139869,87933
18,139869,87934
18,139869,87936
18,139869,87938
在此列表中,我正在創建另一個列表:
18,139869,87718
18,139869,87719
18,139869,87722
18,139869,87723
18,139869,87725
18,139869,87727
18,139869,87751
18,139869,87753
18,139869,87841
18,139869,87848
等等...
我在類方法中使用此Python代碼:
while idx in range(len(self.zoom_list)):
this_Xelement = self.zoom_list[idx]
next_Xelement = self.zoom_list[(idx + 1) % len(self.zoom_list)]
#get diffenrences in line ntries for x and y coordinate
X = int(next_Xelement[1]) - int(this_Xelement[1])
y = int(next_Xelement[2]) - int(this_Xelement[2])
#set start coordinate for Bounding Box
x_start = int(this_Xelement[1])
y_start = int(this_Xelement[2])
#decide witch coordinate to set as end coordinet for rendering Bounding Box
if X == 0:
if y > 1:
x_end = int(this_Xelement[1]) + 1
y_end = int(this_Xelement[2]) + 1
elif y == 1:
bidx = idx
for bidx, row in enumerate(self.zoom_list, bidx):
this_Yelement = self.zoom_list[bidx % len(self.zoom_list)]
next_Yelement = self.zoom_list[(bidx + 1) % len(self.zoom_list)]
y2 = int(next_Yelement[2]) - int(this_Yelement[2])
if y2 == 1:
continue
elif y2 > 1:
x_end = int(this_Xelement[1]) + 1
y_end = int(this_Yelement[2]) + 1
break
elif y2 < 1 and bidx == (len(self.zoom_list) - 1):
x_end = int(this_Xelement[1]) + 1
y_end = int(this_Yelement[2]) + 1
break
idx = bidx
elif X == 1:
x_end = int(next_Xelement[1]) + 1
y_end = int(this_Xelement[2]) + 1
else:
x_end = int(this_Xelement[1]) + 1
y_end = int(this_Xelement[2]) + 1
#create BB coordinates from extracted start and end tile coordinates
r_Up = self.num2deg(int(x_start), int(y_start), self.zoom)
l_Down = self.num2deg(int(x_end) - 0.25, int(y_end) - 0.25, self.zoom)
#create bounding box for rendering with mapnik (left down + right up)
bb = l_Down + r_Up
self.bb_list.append(bb)
idx += 1
有沒有辦法加快速度? 2:48h太長。
python 2.x中的range
創建一個列表。 while謂詞中的表達式每次迭代都會導致列表的創建/銷毀; 創建1,300,000個項目,結果列出1,300,000次。
while idx in range(len(self.zoom_list)): # this is run every iteration
...
idx += 1
通過在xrange
使用for
語句,將更易於閱讀,不會發生列表創建/銷毀的情況。
for idx in xrange(len(self.zoom_list)):
...
另一個小問題:不必要的重復int
調用。
刪除不必要的int
調用。 例如, int(y_start)
, int(y_end)
可以用y_start
, y_end
替換, y_end
y_start
和y_end
已經是int
對象。
另外,如果可能,請事先將self.zoom_lsit
轉換為包含int
以避免重復的int
調用。
更新
我注意到idx
在while
循環內被修改。 但是,關於range
的第一次提及仍然有效; 避免重復撥打range
:
while 0 <= idx < len(self.zoom_list):
...
idx += 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.