2013-04-09 34 views
0

我的意思是想象我有一個空的100 * 100數組,並且在這個數組中有幾千個隨機位置/座標。我需要計算這些座標在「直線」邊緣的15個像素內有多少個座標。到目前爲止,我有這個代碼...計算座標在某個周界內的頻率?

import random 
import pylab 
import numpy       #all import statements 
pylab.close("all") 

x = [(random.randint(0,100)) for i in range(3000)]  #creating list of x coordinates 
y = [(random.randint(0,100)) for j in range(3000)]  #creating list of y coordinates 
array=zip(x,y)             #creating an array by combining the x and y coordinates 
           #end of part 1a 
counter = 0       #start of 1b 
for i in range(100): 
    for j in range(100): 
     if i<=15 or i>=85: 
         if array[i][j]>0: 
           counter=counter+1 
     elif j<=15 or j>=85: 
         if array[i][j]>0: 
           counter=counter+1 

print counter,"random locations within 15 pixels of the edges" 

我該如何糾正代碼?目前我得到一個錯誤閱讀說'元組索引超出範圍'我知道它的數組[i] [j]> 0線,但我不明白它有什麼問題...

+1

'zip'可能不會做你的想法。它不是創建一個100 x 100的數組,而是一個100(x,y)元組的列表。 – Arkady 2013-04-09 19:53:48

+0

所以我該如何糾正它,或者它是一個數組或者讓計數器查看元組? – blablabla 2013-04-09 19:56:35

回答

0

你很近。您正在生成一個稀疏的值網格。如果您先將這些元組放在字典中進行迭代,則可以檢查每個離散位置是否存在邊緣違規。以下是一個工作示例。

edge_dist = 15 
sparse_grid = collections.defaultdict(int) 
for x,y in zip(x,y): 
    sparse_grid[(x,y)] += 1 
for i,j in sparse_grid: 
    if (i <= edge_dist or i >= 100-edge_dist or 
      j <= edge_dist or j >= 100-edge_dist): 
     counter += sparse_grid[(i,j)] 

print "%d random locations within 15 pixels of the edges" % counter 
# 1579 random locations within 15 pixels of the edges 

你在你的版本是得到的錯誤是一個事實,即壓縮是給你的x,y,而不是X-通過-y值的網格的元組。你可以看到你的zip文件應該如何在上面使用。

0

您不需要實際構建數組來計算覆蓋的邊緣點。如果您擔心不會計算相同的座標兩次,則可以使用一組設置刪除重複項。

cords = set(array)        # set removes duplicates 

counter = 0 
for i, j in cords: # or array if you want to count duplicates 
    if i <= 15 or i >= 85 or j <= 15 or j >= 85: 
     counter += 1 

print counter, "random locations within 15 pixels of the edges" 
0

我不能完全肯定我理解你想要達到的,但如果你想利用你的3000個隨機點,看看有多少人都內的100×100正方形的邊15個單位,以下將工作:

sum(not (15 < x < 85 and 15 < y < 85) for x, y in array) 

這利用Python的布爾值TrueFalse也具有整數值(1和0,分別地)的事實。因此,您可以總結一系列的True s和False s來計算真實值。

我使用了否定表達式,因爲它允許我使用Python的不等式鏈來進行實際的邊界測試。表達式not 15 < x < 85似乎比等效的x <= 15 or x >= 85好得多。這可能是主觀的,你的里程可能會有所不同。

+0

我不知道這取決於評價爲1是一個好主意。 – cmd 2013-04-09 20:55:01

+0

@cmd在Python中它非常安全。 'bool'類型是'int'的一個子類,'True == 1和False == 0'對於它的定義非常重要。也許Python 4會打破這一點,但我不會指望它在任何時候發生。 – Blckknght 2013-04-10 00:39:35

0
x = numpy.array(x) 
y = numpy.array(y) 
counter = ((x<=15) | (y<=15) | (x>=85) | (y>=85)).sum()