Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimized method of cutting/slicing sorted lists

Tags:

python

find

list

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]

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

[7,9]

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

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).

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).

Thank you in advance.

like image 379
BorrajaX Avatar asked Nov 29 '12 17:11

BorrajaX


1 Answers

Bisect left and right helper function

#!/usr/bin/env python3

import bisect

def get_slice(list_, left, right):
    return list_[
        bisect.bisect_left(list_, left):
        bisect.bisect_left(list_, right)
    ]

assert get_slice([0, 1, 1, 3, 4, 4, 5, 6], 1, 5) == [1, 1, 3, 4, 4]

Tested in Ubuntu 16.04, Python 3.5.2.