【发布时间】:2019-10-06 23:11:30
【问题描述】:
我正在使用来自here 的函数get_tuples(length, total)
要生成给定长度和总和的所有元组的数组,下面显示了一个示例和函数。创建数组后,我需要找到一种方法来返回数组中给定数量元素的索引。我可以使用.index() 通过将数组更改为列表来做到这一点,如下所示。但是,此解决方案或同样基于搜索的其他解决方案(例如使用np.where)需要花费大量时间来查找索引。由于数组中的所有元素(示例中的数组s)都是不同的,我想知道我们是否可以构造一个一对一的映射,即一个函数,给定数组中的元素,它返回的索引通过对该元素的值进行一些加法和乘法来计算该元素。如果可能的话,有什么想法吗?谢谢!
import numpy as np
def get_tuples(length, total):
if length == 1:
yield (total,)
return
for i in range(total + 1):
for t in get_tuples(length - 1, total - i):
yield (i,) + t
#example
s = np.array(list(get_tuples(4, 20)))
# array s
In [1]: s
Out[1]:
array([[ 0, 0, 0, 20],
[ 0, 0, 1, 19],
[ 0, 0, 2, 18],
...,
[19, 0, 1, 0],
[19, 1, 0, 0],
[20, 0, 0, 0]])
#example of element to find the index for. (Note in reality this is 1000+ elements)
elements_to_find =np.array([[ 0, 0, 0, 20],
[ 0, 0, 7, 13],
[ 0, 5, 5, 10],
[ 0, 0, 5, 15],
[ 0, 2, 4, 14]])
#change array to list
s_list = s.tolist()
#find the indices
indx=[s_list.index(i) for i in elements_to_find.tolist()]
#output
In [2]: indx
Out[2]: [0, 7, 100, 5, 45]
【问题讨论】:
-
你可以访问
get_tuples()的输入吗? -
你是指例子中的参数4和20吗?是的,我设置了这些。
-
好的,但是您为什么不能只计算元素的出现顺序以使用该信息查找?
-
你会怎么做?这正是我想要找到的。应该有一个公式给出数组中的一个元素,例如
[0, 0, 0, 20]会返回 0,...等
标签: python arrays numpy indexing