简体   繁体   English

如何找到给定数字与 Python 列表中每个元素之间的最小差异?

[英]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.

相关问题 如何在python的列表中找到最小的最接近数字 - How to find the smallest closest number in a list in python 我如何在 Python 中的列表中找到最小值或最大值 - How do i find the smallest or largest value in a list in Python 如何找到组内值之间的最小差异 - How can I find the smallest difference between values within a group 如果我有多个最小数字并且想要两个索引,如何在python数组中找到最小数字的索引? - How do I find the Index of the smallest number in an array in python if I have multiple smallest numbers and want both indexes? 在排序列表中查找大于给定数字的最小数字 - Find the smallest number that is greater than a given number in a sorted list 在python列表中找到最小的数字并打印位置 - Find the smallest number in a python list and print the position Python如何查找列表中是否有数字,而不是列表的最后一个数字? - Python How do I find if an number is in a list but is not last number of the list? 如何在python中找到2个值中的哪一个更接近给定数字? - How do I find which of 2 values are closer to a given number in python? 如何在用户在python中提供的2D列表中找到最小,最大值和总数以及平均值? - How do I find the smallest, largest value and total and the average in a 2D list that the user provides in python? 如果有一个整数与字符串绑定最小数字,我如何对列表进行排序? - How do I sort a list if there is an integer tied to a string by the smallest number?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM