如何在数组中查找数组的索引 [英] How to find the index of an array within an array

查看:503
本文介绍了如何在数组中查找数组的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经按照下面显示的方式创建了一个数组;代表3对坐标.我的问题是我似乎无法找到数组中一对特定坐标的索引.

I have created an array in the way shown below; which represents 3 pairs of co-ordinates. My issue is I don't seem to be able to find the index of a particular pair of co-ordinates within the array.

import numpy as np

R = np.random.uniform(size=(3,2))

R

Out[5]: 
array([[ 0.57150157,  0.46611662],
   [ 0.37897719,  0.77653461],
   [ 0.73994281,  0.7816987 ]])

R.index([ 0.57150157,  0.46611662])

返回以下内容:

AttributeError: 'numpy.ndarray' object has no attribute 'index'

我要这样做的原因是,我可以在一个for循环中扩展一个带有坐标对索引的列表.

The reason I'm trying to do this is so I can extend a list, with the index of a co-ordinate pair, within a for-loop.

例如

v = []
for A in R:
v.append(R.index(A)) 

我只是不确定为什么索引功能不起作用,并且似乎找不到解决方法.

I'm just not sure why the index function isn't working, and can't seem to find a way around it.

我是编程新手,请原谅我这是胡说八道.

I'm new to programming so excuse me if this seems like nonsense.

推荐答案

您可以通过将内部数组(坐标)转换为元组来获得所需的结果.

You can achieve the desired result by converting your inner arrays (the coordinates) to tuples.

R = map(lambda x: (x), R);

然后您可以使用R.index((number1,number2));查找元组的索引

And then you can find the index of a tuple using R.index((number1, number2));

希望这会有所帮助!

为了解释上面的代码中发生的事情,map函数遍历(迭代)了数组R中的项目,并用lambda函数的返回结果替换了每个项目. 因此,这等效于以下方面:

To explain what's going on in the code above, the map function goes through (iterates) the items in the array R, and for each one replaces it with the return result of the lambda function. So it's equivalent to something along these lines:

def someFunction(x):
  return (x)

for x in range(0, len(R)):
  R[x] = someFunction(R[x])

因此,它接受每个项目并对其执行操作,然后将其放回列表中.我意识到它可能实际上并没有达到我的预期(返回(x)似乎没有将常规数组更改为元组),但是它确实对您有所帮助,因为我认为通过遍历python可能会创建一个常规数组numpy数组之外的数组.

So it takes each item and does something to it, putting it back in the list. I realized that it may not actually do what I thought it did (returning (x) doesn't seem to change a regular array to a tuple), but it does help your situation because I think by iterating through it python might create a regular array out of the numpy array.

要真正转换为元组,应使用以下代码

To actually convert to a tuple, the following code should work

R = map(tuple, R) 

(贷方为 https://stackoverflow.com/a/10016379/2612012 )

这篇关于如何在数组中查找数组的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆