英文:
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 <= 19
2 <= 24
3 <= 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 <= 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 <= y for x, y in zip(find, t)))
# use random.choice instead to get a random one instead of the first
(11, 44, 6)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论