获取三个数字中最接近的匹配。

huangapple go评论79阅读模式
英文:

How to get the closest match among three numbers

问题

我有一个列表:

[(1, 49, 47), (11, 44, 6), (24, 16, 31), (11, 29, 47), (41, 14, 24), (40, 29, 1), (32, 49, 44), (41, 14, 14), (24, 21, 49), (19, 24, 6)]

还有一个元组(7,2,3),我需要从这个列表中选择一个值,以便根据它们的位置选择新值,使元组中的每个元素都小于或等于所选的新值,例如,如果我选择(19, 24, 6),则条件为真,因为

7 <= 19
2 <= 24
3 <= 6

如何选择新的元组,以使个别值最小?

如果假设数字在左侧具有更高的权重,我可以根据第一个元素对它们进行排序,然后是第二个元素...

但如果数字没有根据其位置具有任何权重,是否有更好的方法来做到这一点?

英文:

I have a list :

[(1, 49, 47), (11, 44, 6), (24, 16, 31), (11, 29, 47), (41, 14, 24), (40, 29, 1), (32, 49, 44), (41, 14, 14), (24, 21, 49), (19, 24, 6)]

And a tuple (7,2,3) I need to choose a value from this list such that every element in the tuple should be less than or equal to the new value selected according to their positions, for example, if I select (19, 24, 6), the condition is true as

7 &lt;= 19
2 &lt;= 24
3 &lt;= 6

How can I select the new tuple such that the individual values are minimum.

If I assume the numbers have a higher weightage towards left, I can sort them based on first element, then the second...

But is there are better way to do this? if the numbers did not have any weightage according to their position?

答案1

得分: 1

以下是翻译好的代码部分:

你可以使用 `all` 和嵌套的推导式

data = [(1, 49, 47), (11, 44, 6), (24, 16, 31), (11, 29, 47), (41, 14, 24), (40, 29, 1), (32, 49, 44), (41, 14, 14), (24, 21, 49), (19, 24, 6)]
find = 7, 2, 3

result = [t for t in data if all(x <= y for x, y in zip(find, t))]
如果你想要找到满足条件的第一个元素你可以使用 `next`

result = next(t for t in data if all(x <= y for x, y in zip(find, t)))
# 要获取第一个以外的随机元素,可以使用 random.choice
(11, 44, 6)
英文:

You could use all and a nested comprehension:

data = [(1, 49, 47), (11, 44, 6), (24, 16, 31), (11, 29, 47), (41, 14, 24), (40, 29, 1), (32, 49, 44), (41, 14, 14), (24, 21, 49), (19, 24, 6)]
find = 7,2,3

result = [t for t in data if all(x &lt;= y for x, y in zip(find, t))]

[(11, 44, 6), (24, 16, 31), (11, 29, 47), (41, 14, 24), (32, 49, 44), (41, 14, 14), (24, 21, 49), (19, 24, 6)]

If you want the first one that satisfies the condition, then you can use next

result = next(t for t in data if all(x &lt;= y for x, y in zip(find, t)))
# use random.choice instead to get a random one instead of the first

(11, 44, 6)

huangapple
  • 本文由 发表于 2023年3月3日 22:04:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75628082.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定