python - 从存在值(检查是否)字典中查找索引
问题描述
我正在使用 python-3.x 并且我想检查字典中是否存在该值(如果存在)然后我想在字典中查找并打印该值的索引号。
这是我的代码示例:
# import numpy
import numpy as np
# my first array
my_array_1 = np.array([[ 1 , 2 , 3 ],
[ 32 , 42 , 11 ],
[ 9 , 21 , 22 ],
[ 9 , 21 , 22 ],
[ 9 , 21 , 22 ],
[ 32 , 42 , 11 ],
[ 1 , 2 , 3 ]])
# here I want to find the unique values from my_array_1
indx = np.unique(my_array_1, return_index=True, return_counts= True,axis=0)
#save the result to dictionary
dic_t= {"my_array_uniq":indx[0],
"counts":indx[1]}
# my 2nd array
my_array_2 = np.array([[ 1 , 2 , 3 ],
[ 32 , 422 , 11 ],
[ 9 , 221 , 22 ],
[ 9 , 221 , 22 ],
[ 9 , 21 , 22 ],
[ 32 , 242 , 11 ],
[ 1 , 22 , 3] ])
for i in range (len(my_array_2)):
# here I want to check if the vlue exist or not
if any((my_array_2[i] == j).all() for j in dic_t["my_array_uniq"]):
######(if it exists print the index number of the existing vlue in dic_t["my_array_uniq"])######
print (50*"*", i, "Yes")
print (my_array_2[i], "\n")
print (dic_t["my_array_uniq"])
else:
print (50*"*", i, "No")
dic_t["my_array_uniq"] = np.vstack((dic_t["my_array_uniq"], my_array_2[i]))
我所需要的只是我尽力找到正确方法的索引号,但它们都不起作用......
解决方案
问题是在测试元素是否存在的行中,您没有将索引保留在找到它的位置。
您应该使用 enumerate 来处理列表中的索引和值:
for i, a in enumerate(my_array_2):
# here I want to check if the vlue exist or not
ix = [k for k,j in enumerate(dic_t["my_array_uniq"]) if (a == j).all()]
if ix:
######(if it exists print the index number of the existing vlue in dic_t["my_array_uniq"])######
print (50*"*", i, "Yes", "at", ix[0])
print (my_array_2[i], "\n")
print (dic_t["my_array_uniq"])
else:
print (50*"*", i, "No")
dic_t["my_array_uniq"] = np.vstack((dic_t["my_array_uniq"], my_array_2[i]))
推荐阅读
- javascript - 如何在此类中在运行时更改类的原型(使用 ES6 类)
- ios - 删除与锻炼相关的所有数据样本
- android - 我们可以从另一个 Fragment B 更改 Fragmet A 的 Linearlayout 的背景颜色吗?没有错误
- python - Keras(Tensorflow)如何计算。最后一层张量的形状?
- vue.js - 从列表中删除 vue 组件总是删除列表中的最后一个元素
- r - as.name 可以用于定位变量并修改其子元素吗?
- kubernetes - Minikube 没有启动,kubectl 连接到服务器被拒绝
- python - 将 xlrd 安装到 python3.6
- c# - Unity多人立方体自动移动?
- c# - Where 子句和 Join 的 LINQ 顺序