将 numpy 数组元素包装为整数
Wrapping a numpy array element to integer
我有一个我试图在循环中访问的子图列表:
index=[5,3,4,1,1,3,4,2,3,4,2,2,3,3,2,4]
subgraph=[[subgraph1],[subgraph2],[subgraph3],[subgraph4],[subgraph5]]
for i in range(len(index)):
for j in range(i+1,len(index)):
if index[j]==index[i]
continue
testgraphi=copy.copy(subgraph[index[i]])
testgraphj=copy.copy(subgraph[index[j]])
所以在第一个循环中,testgraphi
会被分配 subgraph5
,testgraphj
会被分配 subgraph3
。但是,当我尝试此方法时,我 return 收到错误 list indices must be integers, not numpy.float64
。这是合乎逻辑的,因为 index
在我的程序的整个范围内实际上被初始化为一个 numpy 数组(并且它必须保持这种状态)。所以我的问题是,我如何转换这个值,以便它可以用作我的子图列表的索引?这样在初始化testgraph
的时候,会取回循环所在的index的值,并以此来定义return?
哪个列表索引
你可以试试这个:
new_index = np.asarray(index, dtype=np.int32)
这应该将索引中的所有值都转换为整数。
您可以通过以下操作将 numpy.float64
转换为浮点数:var.item()
。然后将其转换为整数,以便将其用作索引:int(var.item())
我有一个我试图在循环中访问的子图列表:
index=[5,3,4,1,1,3,4,2,3,4,2,2,3,3,2,4]
subgraph=[[subgraph1],[subgraph2],[subgraph3],[subgraph4],[subgraph5]]
for i in range(len(index)):
for j in range(i+1,len(index)):
if index[j]==index[i]
continue
testgraphi=copy.copy(subgraph[index[i]])
testgraphj=copy.copy(subgraph[index[j]])
所以在第一个循环中,testgraphi
会被分配 subgraph5
,testgraphj
会被分配 subgraph3
。但是,当我尝试此方法时,我 return 收到错误 list indices must be integers, not numpy.float64
。这是合乎逻辑的,因为 index
在我的程序的整个范围内实际上被初始化为一个 numpy 数组(并且它必须保持这种状态)。所以我的问题是,我如何转换这个值,以便它可以用作我的子图列表的索引?这样在初始化testgraph
的时候,会取回循环所在的index的值,并以此来定义return?
你可以试试这个:
new_index = np.asarray(index, dtype=np.int32)
这应该将索引中的所有值都转换为整数。
您可以通过以下操作将 numpy.float64
转换为浮点数:var.item()
。然后将其转换为整数,以便将其用作索引:int(var.item())