从Python字典中根据索引获取特定键。

huangapple go评论73阅读模式
英文:

Obtain specific key from python dictionary based on index

问题

我需要确定特定索引指向两个字典中的哪个对象(在这种情况下是图像数组)。

dict_count 表示我有 400 个对象 1,300 个对象 2 等等。

dict_object 包含对象(最大计数在 dict_count 中提到)

现在,如果我给定一个索引 = 450,我需要从 dict_object 中获取 '标签 2' 下的第 50 个对象。

现有代码(可能不是有效的)

Matrix = [[-1 for x in range(sum(dict_count.values()))] for y in range(2)] 
i = 0
index = 450
for k in dict_object.keys():
    for images in dict_object[k]:
        Matrix[0][i] = images
        Matrix[1][i] = k
        i += 1
        
obj = Matrix[index-1][0]
label = MAtrix[index-1][1]

如何有效地执行这个任务? TIA!

英文:

I need to identify which object(image array in this case) a particular index points to from two dictionaries.

dict_count = {1: 400, 2:300, 3:200, 4: 100} 

dict_count says I have 400 of object 1, 300 of object 2 and so on.

dict_object = {1 :[obj1, obj2 ... obj400], 2 :[obj1, obj2 ...obj300], 3 :[obj1, obj2 ...], 4 :[obj1, obj2 ...] 

dict_object contains the objects (max count is mentioned in dict_count)

Now, if I am given an index = 450, I need to get the 50th object under 'label 2' from the dict_object.

Existing code (probably not efficient)

Matrix = [[-1 for x in range(sum(dict_count.values()))] for y in range(2)] 
i = 0
index = 450
for k in dict_object.keys():
    for images in dict_object[k]:
        Matrix[0][i] = images
        Matrix[1][i] = k
        i += 1
        
obj = Matrix[index-1][0]
label = MAtrix[index-1][1]

How do I do this efficiently? TIA!

答案1

得分: 3

不要迭代一次一个索引,而是通过dict_count进行分块迭代:

def get_obj(i):
    for k, c in dict_count.items():
        if i < c:
            return dict_object[k][i]
        else:
            i -= c
    raise IndexError(f"索引 {i} 超出 {sum(dict_count.values())}")
英文:

Rather than iterating through indices 1 at a time, iterate through dict_count so you can do it in chunks:

def get_obj(i):
    for k, c in dict_count.items():
        if i &lt; c:
            return dict_object[k][i]
        else:
            i -= c
    raise IndexError(f&quot;index {i} exceeds {sum(dict_count.values())}&quot;)

huangapple
  • 本文由 发表于 2023年3月7日 14:15:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75658569.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定