在元组列表中查找最小值和最大值,即(最小值,最大值),(最大值,最小值)?
我有一个元组列表,(x1,y1),(x2,y2) 等,我想找到的是其中 x 是最大值、y 是最小值以及各种其他组合的元组。我已经能够找到 x 是最大值和 y 是最大值的位置,以及 x 是最小值和 y 是最小值的位置,但我不确定如何首先按最大值过滤,然后按最小值过滤,反之亦然。
这是我到目前为止所尝试过的:
coords = [(200,200),(40,150),(50,180),(20,200),(200,20),(20,20)]
c1 = max(coords, key=operator.itemgetter(0))
c2 = min(coords,key = operator.itemgetter(0))
c3 = max(coords,key = operator.itemgetter(1))
c4 = min(coords,key = operator.itemgetter(1))
#returns (200,200),(20,200),(200,200),(200,20))
#wanted (200,200),(20,200), (200, 20), (20,20)
#(max,max), (min,max), (max,min), (min,min) or some order of this
实际上“coords”有超过 6 个元组。例如,当我想要 coords[0] 和 coords[3] 时,我最终会为 c1 和 c3 返回相同的坐标,因此(max,max)然后是(min,max)。我是否使事情过于复杂化,或者是否有更简单的方法来解决这个问题?输出的顺序并不特别重要,只要每次坐标更改时输出的顺序相同即可。我已经简化了这个问题并发布在这里,所以可能会有一些错误,抱歉。谢谢!
I have a list of tuples, (x1,y1),(x2,y2) etc and what I'd like to find is the tuple where x is a maximum and y is a minimum and various other combinations. I have been able to find where x is a maximum and y is a maximum, and when x is a minimum and y is a minimum, but I'm not sure how to first filter by maximum, then by minimum and vice versa.
Here's what I've tried so far:
coords = [(200,200),(40,150),(50,180),(20,200),(200,20),(20,20)]
c1 = max(coords, key=operator.itemgetter(0))
c2 = min(coords,key = operator.itemgetter(0))
c3 = max(coords,key = operator.itemgetter(1))
c4 = min(coords,key = operator.itemgetter(1))
#returns (200,200),(20,200),(200,200),(200,20))
#wanted (200,200),(20,200), (200, 20), (20,20)
#(max,max), (min,max), (max,min), (min,min) or some order of this
In reality 'coords' has more than 6 tuples. I end up with the same coordinate being returned for c1 and c3 for example when I wanted coords[0] and coords[3], so (max,max) and then (min,max). Am I over-complicating things, or is there a much simpler way to solve this? The order of the output doesn't particularly matter as long as it is the same order every time the coords change. I have simplified this issue to post here so there may be some errors sorry. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种可能的方法是识别 x 和 y 的最大值和最小值,用这些值生成所有可能的元组,并检查这些元组是否存在于列表中。
鉴于您的澄清评论,我认为这足以满足您的需求。如果输入数据不能可靠地包含您正在寻找的组合,则您必须更具体地说明您想要的内容。
就此而言,如果您保证输入数据中包含您想要的组合,则可以删除
if
行并仅输出所有排列。但验证它们是否确实存在可能是明智之举。A possible approach is to identify the maximum and minimum values of x and y, generate all possible tuples with those values, and check if those tuples exist in the list.
Given your clarifying comments, I think that's sufficient for your needs. If the input data didn't reliably contain the combinations you're looking for, you'd have to be more specific about what you want.
For that matter, if you are guaranteed that the combinations you want are in the input data, you could remove the
if
line and just output all of the permutations. But it's probably wise to verify they are actually there.