我有一个用Python编写的代码,类似于以下内容:
def adamic_adar_prediction(graph):
adjacencyMatrix = graph.get_adjacency()
AAMatrix = adamic_adar_score(graph)
AAMatrix = np.array(AAMatrix)
i = (-AAMatrix ).argsort(axis=None, kind='mergesort')
j = np.unravel_index(i, AAMatrix .shape)
sortedList = np.vstack(j).T
print(sortedList.size)
print(sortedList[1658943])
print(sortedList[1658945])
虽然第一次打印的结果是3,316,888,但我在上次打印时收到以下错误:
IndexError: index 1658944 is out of bounds for axis 0 with size 1658944
知道我的数组出现这个错误的原因吗?
答案 0 :(得分:2)
您的array
中没有足够的元素,例如:
In [5]: import numpy as np
In [6]: a = np.array([1,2])
In [8]: a[2] # there is no element at 2nd index
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-8-016a87a854bc> in <module>()
----> 1 a[2]
IndexError: index 2 is out of bounds for axis 0 with size 2
答案 1 :(得分:2)
考虑到你的问题是多么神秘,我会继续尝试使用try / except循环来测试它,以确保代码超过了这一点并且仅在索引1658944处出现问题...
类似的东西:
for x in range(sortedList.size):
try:
sortedList[x]
except:
print "no index at", x
报告您的结果。
答案 2 :(得分:1)
感谢所有评论。我想我的问题是sortedList.size返回数组中元素的总数,而我期待数组中的元组数(因为sortedList是元组[[],[],...]的列表)。所以我使用sortedList.shape