字典键的不同列表值

字典键的不同列表值

本文介绍了字典键的不同列表值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个字典,其中的关键是3个元素的元组,值为列表,如下所示:

I created a dictionary, where the key is a tuple of 3 elements and the value is a list, as so:

dic = {}
l = []

for z in range(0,20):
    for y in range(0,150):
        for x in range(0,200):
            for j in range(0,4):
                l.append(self.images[j].GetScalarComponentAsDouble(x, y, z, 0))
            dic.update({(x,y,z) : l})

print(dic[(25,25,5)])

图像只是一个图像数据列表,从那里我获得强度值,并将该值存储在列表 l

imagesis just a list of image data, from where I get the intensity value and store this value in list l.

我想在字典中看到的最终结果将有以下形式的项目:

The final result I want to see in the dictionary will have items in this form:

{(...),
 (150,120,10): [2,5,3,9],
 (130,100,16): [4,1,1,8],
(...)}

但是由于列表始终被附加元素而不被重新设置,我无法获取此结果。

But because the list is always being appended with elements without being reseted, I cannot obtain this result.

如何重置e列表 l 以便每个元组键都有自己的列表值?

How can I reset the list l so that every tuple key has its own list value?

推荐答案

使用 itertool 产品函数和列表推导可以使用另一种方法来写:

There is an alternative way to write this, using itertool's product function and list comprehensions:

from itertools import product

dic = {}
for z, y, x in product(range(20), range(150), range(200)):
    dic[x, y, z] = [self.images[j].GetScalarComponentAsDouble(x, y, z, 0)
                     for j in range(4)]

itertools 通常可以帮助您避免深度嵌套,并且列表理解允许您创建列表并将其分配给一行中的字典(尽管在本示例中我可以分为两个可读性)。

Functions in itertools often help you avoid deep nesting, and the list comprehension allows you to create the list and assign it to the dictionary in one line (although I broke out into two for readability in this example).

实际上,由于python字典无序,假设您的 GetScalarComponentAsDouble 没有任何副作用,更改循环次序 x,yz 代码更容易遵循,同时产生相同的输出。

Actually, since python dictionaries are unordered, assuming your GetScalarComponentAsDouble doesn't have any side effects, changing the loop order of x, y z makes the code easier to follow while producing the same output.

from itertools import product

dic = {}
for x, y, z in product(range(200), range(150), range(20)):
    dic[x, y, z] = [self.images[j].GetScalarComponentAsDouble(x, y, z, 0)
                     for j in range(4)]

这篇关于字典键的不同列表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 08:10