簡體   English   中英

用python返回成對數組中元組的索引

[英]Return index of tuple in array of pairs with python

我有兩個(x,y)坐標數組。 在對它們執行數學運算后,我詢問程序哪個答案小於300。

我還想告訴我使用了兩對(x,y)坐標(一組來自數組a,一組來自數組b)來計算此答案。 我怎樣才能做到這一點?

Nb:數組的內容是隨機的,它們的長度由用戶選擇(如下所示)。

這是我的代碼:

#Create arrays
xy_1 = [(random.randint(0,1000), random.randint(0,1000)) for h in range((int(raw_input(“Type your first array’s range: “)))]
a = array([xy_1])

xy_2 = #same as above
b = array([xy_2])

(如果用戶選擇xy_1具有3對,xy_2具有2對,則輸出將如下所示:

a[(1,5),(300,70),(10,435)]
b[(765,123),(456,20)]

每次都有不同的數字,因為它是隨機數生成器。)

#Perform mathematical operation
for element in a:
    for u in element:
        for element in b:
            for h in element:
                ans = (((u[0] - h[0])**2) + ((u[1] - h[1])**2))

                if ans <= 300:
#Problem here       print "a: " + str(np.nonzero(u)[0]) + "b: " + str(np.nonzero(h)[0]) + "is less than 300"
                else:
#and here           print "a: " + str(np.nonzero(u)[0]) + "b: " + str(np.nonzero(h)[0]) + "is more than 300"

當前,輸出如下所示:

a: [0 1] b: [0 1] is less than 300

要么

a: [0 1] b: [0 1] is more than 300

但是正如我上面所說,我想告訴我a和b中每個(x,y)對的索引(或數組的任何名稱),看起來像這樣:

a: 15 b: 3 is less than 300

(如果是a中的第15對坐標和b中的第3對坐標產生的結果小於300)。

我曾嘗試將zip與itertools.count一起使用,但由於重復迭代的次數過多,因此無法解決。

import numpy as np

h = int(raw_input("Type your first array's range: "))
xy_1 = np.random.randint(0, 1000, (h, 2))
a = xy_1

h = int(raw_input("Type your first array's range: "))
xy_2 = np.random.randint(0, 1000, (h, 2))
b = xy_2
ans = (a[:, 0] - b[:, 0, None]) ** 2 + (a[:, 1] - b[:, 1, None]) ** 2

a_indexes, b_indexes = np.nonzero(ans < 300)

只需循環搜索結果索引以打印它們。 盡管您似乎在這里計算距離,但應在檢查結果是否np.sqrt 300之前添加結果的np.sqrt

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM