[英]How do I find the smallest difference between a given number and every element in a list in Python?
Say I have:说我有:
[1, 2, 3, 4]
and the integer和整数
6
I want to compare 6
with every element in the list and return the element with the smallest absolute value difference which in this case is 4
.我想将6
与列表中的每个元素进行比较,并返回绝对值差异最小的元素,在本例中为4
。 Is there an efficient Numpy
way to do it?有没有一种有效的Numpy
方法来做到这一点?
You can use argmin
on the absolute difference to extract the index, which can then be used to extract the element:您可以在绝对差上使用argmin
来提取索引,然后可以使用它来提取元素:
a = np.array([1, 2, 3, 4])
a[np.abs(a - 6).argmin()]
# 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.