列表中 numpy 数组的索引

eya*_*ler 8 python numpy

尝试从 python 列表中索引或删除 numpy 数组项,第一项不会按预期失败。

import numpy as np

# works:
lst = [np.array([1,2]), np.array([3,4])]
lst.index(lst[0])

# fails with: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
lst = [np.array([1,2]), np.array([3,4])]
lst.index(lst[1])

Run Code Online (Sandbox Code Playgroud)

我理解为什么第二个失败,我想理解为什么第一个有效。

Con*_*tin 3

因为它没有利用数组的eq方法,而只是比较id两个对象的 s:

lst = [np.array([1,2]), np.array([3,4])]
lst[0]                                  => array([1, 2])
lst[1]                                  => array([3, 4])
lst[0] == lst[1]                        => array([False, False], dtype=bool)
id(lst[0])                              => 140232956554776
id(lst[1])                              => 140232956554960
lst.index(lst[0])                       => 0
lst.index(lst[1])                       => 1
lst.index(lst[0]) == lst.index(lst[1])  => False
Run Code Online (Sandbox Code Playgroud)

为了获得您想要的行为,您需要利用数组的 进行比较eq,例如:

lst.index(lst[0].tolist()) => 0
lst.index(lst[1].tolist()) => 1
Run Code Online (Sandbox Code Playgroud)

或者:

lst.index(lst[0].tostring()) => 0
lst.index(lst[1].tostring()) => 1
Run Code Online (Sandbox Code Playgroud)

但这并不是处理数据的有效方法,因为您要将数组转换为列表或字符串。