我有一个sorted list
.例如,my list
是:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
实际上,我有我的类的对象列表,int property
,列表在其上排序。
我想计算对象的数量,其值在two values
之间this property
。
我正在寻找以下等效的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]