繁体   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