剪切/切片排序列表的优化方法 [英] Optimized method of cutting/slicing sorted lists

查看:96
本文介绍了剪切/切片排序列表的优化方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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]

这篇关于剪切/切片排序列表的优化方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆