Я использую 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]))
Мой плохой, это должно быть enumerate(my_array_2)
. Сообщение отредактировано. (Я провел тест с именами переменных, отличными от ваших, и ошибочно все объединил :-()
Огромное спасибо за помощь буду читать про перечислять :)
Я получаю этот ошибка
ValueError: too many values to unpack (expected 2)
из этой строкиfor i, a in my_array_2:
я не уверен