【问题标题】:find the index from the exists value (check if) dictionary从存在值(检查是否)字典中查找索引
【发布时间】:2019-10-12 23:24:48
【问题描述】:

我正在使用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])) 

我所需要的只是索引号,我已尽力找到正确的方法,但它们都不起作用......

【问题讨论】:

    标签: python python-3.x numpy indexing


    【解决方案1】:

    问题是在测试元素是否存在的那一行中,你并没有在找到它的地方保留索引。

    您应该使用 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]))
    

    【讨论】:

    • 我从这条线for i, a in my_array_2:得到这个错误 ValueError: too many values to unpack (expected 2)我不确定
    • 我的错应该是enumerate(my_array_2)。帖子已编辑。 (我用不同于你的变量名做了一些测试,并且错误地合并了所有内容:-()
    • 非常感谢您的帮助,我将阅读有关枚举的内容:)
    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 2013-06-22
    • 2012-01-03
    • 2019-02-13
    相关资源
    最近更新 更多