[英]Reducing a X,Y,Z list to an X,Y list and retrieve the min & max X of the XY PTS
[英](x,y) pair for max z value in list
我有一個列表列表,例如:
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]]
max
函數: maxz = max(list_, key=lambda x: x[3])
maxz
分配給列表list_
的項目,最大值為索引3(z值)。 然后可以提取xi和yi值: xi, yi = (maxz[1], maxz[2])
nodes
列表進行排序,則可以將sorted
函數與key
一起使用: maxz_levels = sorted(nodes, key=lambda x: x[3], reverse=True)
,然后刪除第一項。 maxz_levels = [] for i in set([(i[1], i[2]) for i in nodes]): m = sorted(filter(lambda x: x[1] == i[0] and x[2] == i[1], nodes))[-1] maxz_levels.append((m[1], m[2], m[3]))
說明:
for
循環遍歷nodes
中所有(x, y)
組合的列表 z
值對具有當前(x, y)
值的nodes
中所有項目的列表進行排序(x, y)
並獲取最后一個( z
值最大的項目)。 #!/usr/bin/env python3
nodes = [['1','1','1','2'],['2','1','1','3'],['3','0','0','5'],['4','0','0','4']]
d = {}
for z in nodes:
x = (z[1], z[2])
if x not in d:
d[x] = z[3]
elif d[x] < z[3]:
d[x] = z[3]
output = []
for x in d:
output.append(x+(d[x],))
print(output)
輸出:
[('0', '0', '5'), ('1', '1', '3')]
如果您的商品是按X和Y訂購的,則:
from itertools import groupby
from operator import itemgetter
nodes = [['1','1','1','2'],['2','1','1','3'],['3','0','0','5'],['4','0','0','4']]
result = [max(g, key=itemgetter(3))[1:] for k, g in groupby(nodes, itemgetter(1, 2))]
# [['1', '1', '3'], ['0', '0', '5']]
否則,您可以提供sorted(nodes, key=itemgetter(1, 2))
代替groupby
的nodes
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.