【问题标题】:Find lists items closest to certain values in Python在 Python 中查找最接近某些值的列表项
【发布时间】:2014-05-23 21:31:13
【问题描述】:

我有一个排序浮点列表y,以及一个未排序浮点列表x

现在,我需要找出x 中的每个元素,它位于y 的哪个值之间,最好是通过y 的索引。例如,如果

y=[1,2,3,4,5]

x[0]=3.5 

我需要x 的索引0 的输出为(2,3),因为3.5 介于y[2]y[3] 之间。

基本上,我猜这与将y 视为垃圾箱边缘并将x 分类到这些垃圾箱相同。

你最简单的方法是什么?

【问题讨论】:

  • 尝试先写一些代码。您可能会惊讶自己并找到最简单的方法。
  • 您是否尝试过实际对 x 进行排序?

标签: python nearest-neighbor bins


【解决方案1】:

我会使用zip(Python 2.x 中的itertools.izip)来实现:

from itertools import islice#, izip as zip # if Python 2.x

def nearest_neighbours(x, lst):
    for l1, l2 in zip(lst, islice(lst, 1, None)):
        if l1 <= x <= l2:
            return l1, l2
    else:
        # ?

示例用法:

>>> nearest_neighbours(3.5, range(1, 6))
(3, 4)

如果x 不在lst 中的任何对之间(即替换# ?!)如果您想要索引(尽管您的示例没有使用它们),您必须决定要发生什么,和enumerate一起玩吧。

【讨论】:

    【解决方案2】:

    谢谢 - 我知道如何逐步编写代码。但是,我一直在寻找一个漂亮/简单/优雅的解决方案,现在我正在使用 numpy.digitize(),这对我来说看起来很漂亮并且效果很好。

    【讨论】:

      【解决方案3】:

      问:你最简单的方法是什么?

      我认为你应该看看这个伪代码,而不是给你代码,然后尝试编写你自己的代码!如果你想自学,不要只是从互联网上复制粘贴代码!

      伪代码:

      // Assume that when you have a tie,
      // you put the number in the smallest range
      // Here, b is between 2.1 and 3.5, instead of
      // 3.5 and 4.1
      float a[5] = {0.1, 1.1, 2.1, 3.5, 4.1}; // your y
      float b = 3.5;                          // your x
      
      // counter for the loop and indexes. Init i to second element
      integer i = 1, prev = -1, next;
      
      // while we are not in the end of the array
      while(i < 5) {
          // if b is in the range of ( a(i-1), a(i) ]
          if(b <= a[i] && b > a[i - 1]) {
          // mark the indexes
              prev = i - 1;
              next = i;
          }
      
          // go to next element
          i++;
      }
      
      if(prev = -1)
          print "Number is not between some numbers"
      else
          print "prev, next"
      

      我认为这可以让你理解重点,然后能够为你选择最简单的方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-20
        • 1970-01-01
        • 2012-11-14
        • 2015-07-26
        • 2020-02-13
        • 2017-06-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多