python - 如何计算排序列表中两个值之间的元素?

标签 python python-2.7 sorting binary-search lower-bound

我有一个排序列表。例如,我的列表是:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

实际上,我有我的类的具有 int 属性 的对象列表,列表已按其排序。

我想计算此属性的值在两个值之间的对象数量。

我正在寻找以下 python 等效项。

int main () {
  int myints[] = {10,20,30,30,20,10,10,20};
  std::vector<int> v(myints,myints+8);           // 10 20 30 30 20 10 10 20

  std::sort (v.begin(), v.end());                // 10 10 10 20 20 20 30 30

  std::vector<int>::iterator low,up;
  low=std::lower_bound (v.begin(), v.end(), 20); //          ^
  up= std::upper_bound (v.begin(), v.end(), 20); //                   ^

  std::cout << "lower_bound at position " << (low- v.begin()) << '\n';
  std::cout << "upper_bound at position " << (up - v.begin()) << '\n';

  std::cout << "MY_RESULT IS" << (up - v.begin())  - (low- v.begin()) << '\n';

  return 0;
}

最佳答案

我会使用bisect模块(因为它使用二分搜索,给它一个O(log n)复杂度)来对两边进行二分,就像这样:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

import bisect

def find_ge(a, low, high):
    i = bisect.bisect_left(a, low)
    g = bisect.bisect_right(a, high)
    if i != len(a) and g != len(a):
        return a[i:g]
    raise ValueError

输出:

>>>find_ge(my_list, 3, 6)
[3, 4, 5, 6]

关于python - 如何计算排序列表中两个值之间的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29015459/

相关文章:

python - 将 wxPanel 保存到图像

javascript - 在Javascript中按字母顺序对字符串进行排序

python - 为什么我的 Flask 应用程序在 Heroku 上被检测为 node.js

python - 在 Python 中提供测试数据

python - Pygame 动画 - IndexError : list index out of range

python - 通过递归生成元素列表

python - 使用 python mechanize 和具有随机代理支持的 urllib2

Python:setup.py 缺失:没有这样的文件或目录

c++ - 使用变量索引对 vector 的 vector 进行排序

C# DataGridView 虚拟模式 : Enable sorting