[英]3D list indexing- how to get max(z) for a specific x,y
I have a list with 3D index and for each combination (x,y,z) I have a value. 我有一个带有3D索引的列表,对于每个组合(x,y,z)我都有一个值。 I would like to know if there is a way to get the max z for a specific x,y. 我想知道是否有一种方法可以获取特定x,y的最大值z。
Example: 例:
a=defaultdict(list)
...
a = {(0,0,1): 5, (0,0,2): 1, (0,0,3): 4}
How to get the max(z) for (x=0,y=0) (which should be 3)? 如何获得(x = 0,y = 0)(应该为3)的max(z)?
I need to use this kind of data structure, because I have a dynamic 3 dimensional matrix with unknown z (heterogenous data over Z). 我需要使用这种数据结构,因为我有一个动态的3维矩阵,其中z未知(Z上的异构数据)。
How about: max(b[2] for b in a.keys() if b[0] == 0 and b[1] == 0)
怎么样: max(b[2] for b in a.keys() if b[0] == 0 and b[1] == 0)
This uses a generator expression to return the z-coordinate of those values where x and y is 0. 这使用生成器表达式返回x和y为0的那些值的z坐标。
In case you need this for any of all possible combinations of x and y, i suggest that you should reorder your data, such that a tuple of x and y is a key, whereas the corresponding z is the value. 如果您需要x和y的所有可能组合中的任何一个,我建议您应该对数据重新排序,以使x和y的元组为键,而对应的z为值。 Then you can simply find the max z: 然后,您可以简单地找到最大z:
from collections import defaultdict
a = {(0,0,1): 5, (0,0,2): 1, (0,0,3): 4, (1,0,2): 5}
b = defaultdict(list)
for xyz in a:
xy = xyz[:-1]
z = xyz[-1]
b[xy].append(z)
max(b[(0,0)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.