优化的切割/切片排序列表的方法

2022-01-20 00:00:00 python list find

问题描述

在 Python 中是否有任何预制的优化工具/库来剪切/切片小于"值的列表?

Is there any pre-made optimized tool/library in Python to cut/slice lists for values "less than" something?

问题来了:假设我有一个类似的列表:

Here's the issue: Let's say I have a list like:

a=[1,3,5,7,9]

我想删除所有 <= 6 的数字,所以结果列表将是

and I want to delete all the numbers which are <= 6, so the resulting list would be

[7,9]

6 不在列表中,所以我不能使用列表的内置 index(6) 方法.我可以这样做:

6 is not in the list, so I can't use the built-in index(6) method of the list. I can do things like:

#!/usr/bin/env python
a = [1, 3, 5, 7, 9]
cut=6
for i in range(len(a)-1, -2, -1):
    if a[i] <= cut:
        break
b = a[i+1:]
print "Cut list: %s" % b

如果要从中剪切的索引接近列表的末尾,这将是一种相当快捷的方法,但如果项目接近列表的开头(假设我想删除所有>2的项目,会有很多迭代).

which would be fairly quick method if the index to cut from is close to the end of the list, but which will be inefficient if the item is close to the beginning of the list (let's say, I want to delete all the items which are >2, there will be a lot of iterations).

我也可以使用二进制搜索等实现我自己的 find 方法,但我想知道是否有一个更广泛的内置库来处理我可以在其他情况下重用的此类事物(例如, 如果我需要删除所有 >=6).

I can also implement my own find method using binary search or such, but I was wondering if there's a more... wide-scope built in library to handle this type of things that I could reuse in other cases (for instance, if I need to delete all the number which are >=6).

提前谢谢你.


解决方案

你可以使用 bisect 模块 执行排序搜索:

You can use the bisect module to perform a sorted search:

>>> import bisect
>>> a[bisect.bisect_left(a, 6):]
[7, 9]

相关文章