使用 python 查找列表中唯一的最大值
我有一个点列表,如下所示,
points=[ [x0,y0,v0], [x1,y1,v1], [x2,y2,v2].......... [xn,yn,vn]]
其中一些点具有重复的 x,y 值。我想要做的是提取唯一的最大值 x,y 点
例如,如果我有点 [1,2,5] [1,1,3] [1,2,7] [1, 7,3]
我想获取列表[1,1,3] [1,2,7] [1,7,3]
我如何在 python 中执行此操作?
谢谢
I have a list of points as shown below
points=[ [x0,y0,v0], [x1,y1,v1], [x2,y2,v2].......... [xn,yn,vn]]
Some of the points have duplicate x,y values. What I want to do is to extract the unique maximum value x,y points
For example, if I have points [1,2,5] [1,1,3] [1,2,7] [1,7,3]
I would like to obtain the list [1,1,3] [1,2,7] [1,7,3]
How can I do this in python?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
例如:
即:按 xy 对点进行排序和分组,对于具有固定 xy 的每个组,选取具有最大 z 的点。如果您熟悉 itertools (你应该如此,它确实是一个非常强大且有用的模块!)。
或者,您可以构建一个字典,其中
(x,y)
元组作为键,z
列表作为值,然后对该字典进行最后一次传递以选择最大z
对于每个(x, y)
,但我认为排序和分组方法更可取(除非你有数百万个点,以至于排序的大 O 性能令人担忧我猜是出于可扩展性的目的)。For example:
that is: sort and group the points by xy, for every group with fixed xy pick the point with the maximum z. Seems straightforward if you're comfortable with itertools (and you should be, it's really a very powerful and useful module!).
Alternatively you could build a dict with
(x,y)
tuples as keys and lists ofz
as values and do one last pass on that one to pick the maxz
for each(x, y)
, but I think the sort-and-group approach is preferable (unless you have many millions of points so that the big-O performance of sorting worries you for scalability purposes, I guess).您可以使用
dict
来实现此目的,使用 属性表示“如果给定的键出现多次,则与其关联的最后一个值将保留在新字典中。”此代码对点进行排序以确保最高值出现在后面,创建一个字典,其键是前两个值的元组,其值是第三个坐标,然后将其转换回列表可能有一种方法可以进一步改进它,但它满足您的所有要求。
You can use
dict
achieve this, using the property that "If a given key is seen more than once, the last value associated with it is retained in the new dictionary." This code sorts the points to make sure that the highest values come later, creates a dictionary whose keys are a tuple of the first two values and whose value is the third coordinate, then translates that back into a listThere may be a way to further improve that, but it satisfies all your requirements.
如果我理解你的问题..也许使用字典将
(x,y)
映射到 max z像这样(未测试)
虽然顺序会丢失
If I understand your question .. maybe use a dictionary to map
(x,y)
to the max zsomething like this (not tested)
Though the ordering will be lost