我有一个列表列表,例如:
nodes =[[nodeID,x,y,z],....]
我想找到:
xi,yi for zi=zmax given zmax= max z for same x,y
并将其存储(xi,yi,zi)
在另一个列表中。
我可以这样做:
nodes=[[literal_eval(x) for x in item] for item in nodes]
maxz_levels=[]
for i,row in enumerate(nodes):
fe=0
maxz=0
nodeID,x,y,z=row
for j,line in enumerate(nodes):
nodeID2,x2,y2,z2=line
if x==x2 and y==y2 and z2>maxz:
maxz=z2
if len(maxz_levels)==0:
maxz_levels.append([x, y, maxz])
else:
for row2 in maxz_levels:
if row2[0]==x and row2[1]==y:
fe=1
if fe==0:
maxz_levels.append([x, y, maxz])
但这需要很长时间......所以我想到了使用字典,但我没有找到一种简单的方法来做我想做的事。我的代码是:
dic1=defaultdict(list)
for nodeID,x,y,z in nodes:
dic1[(x,y)].append((nodeID,z))
for key in dic1:
dic1[key].sort( key=lambda x:float(x[1]) )
for j,row in enumerate(nodes):
nodeID,x,y,z=row
z_levels=[item[1] for item in dic1[(x,y)]]
#How to find easily and quickly the max of z_levels and the associated (x,y) coordinates?
有任何想法吗?谢谢
编辑:示例:
nodes = [['1','1','1','2'],['2','1','1','3'],['3','0','0','5'],['4','0','0','4'],['5','1','2','4'],['6','0','0','40'],['7','0','10','4'],['8','10','0','4'],['9','0','0','4'],['10','2','1','4']]
我想找到:
maxz_levels = [[1, 1, 3], [0, 0, 40], [1, 2, 4], [0, 10, 4], [10, 0, 4], [2, 1, 4]]