最大Z值我有名單,如名單:(X,Y)對在列表
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]]
你應該在我認爲的第一個循環內初始化'maxz'。它不會回答你的問題,但我不確定你現在的解決方案是否有效。 –
是的,你是對的!但在我的情況下,它的作品,因爲馬克斯總是相同:) – jpcgandre