我有一个像这样的数组:
[[ 36 119]
[ 36 148]
[ 36 179]
[ 67 209]
[ 69 84]
[ 96 240]]
和这样的字典:
{84: [36, 119], 85: [36, 148], 86: [36, 160]}
我想检查数组的任何值是否存在于字典中,然后返回数字。对于上面的例子,它应该返回84,85。我试着用
比较pairs = zip(array, dict)
print(any(x != y for x, y in pairs))
虽然我得到一个错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
您可以使用np.isin
和np.ndarray.all
:
>>> pairs = {84: [36, 119], 85: [36, 148], 86: [36, 160]}
>>> array
array([[ 36, 119],
[ 36, 148],
[ 36, 179],
[ 67, 209],
[ 69, 84],
[ 96, 240]])
>>> [k for k, v in pairs.items() if np.isin(v, array).all()]
[84, 85]
像这样?
>>> my_dict = {84: [36, 119], 85: [36, 148], 86: [36, 160]}
>>> x = np.array([[ 36, 119], [ 36, 148], [ 36, 179], [ 67, 209], [ 69 ,84],[96,240]])
>>> [keys for (keys, value) in my_dict.items() if (x == value).all(axis=1).any()]
[84, 85]