Skip to content Skip to sidebar Skip to footer

Optimized Method Of Cutting/slicing Sorted Lists

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 wan

Solution 1:

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

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

Solution 2:

bisect.bisect_left is what you are looking for, I guess.

Solution 3:

If you just want to filter the list for all elements that fulfil a certain criterion, then the most straightforward way is to use the built-in filter function.

Here is an example:

a_list = [10,2,3,8,1,9]

# filter all elements smaller than 6:filtered_list = filter(lambda x: x<6, a_list)

the filtered_list will contain:

 [2, 3, 1]

Note: This method does not rely on the ordering of the list, so for very large lists it might be that a method optimised for ordered searching (as bisect) performs better in terms of speed.

Solution 4:

Bisect left and right helper function

#!/usr/bin/env python3import bisect

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

Solution 5:

Adding to Jon's answer, if you need to actually delete the elements less than 6 and want to keep the same reference to the list, rather than returning a new one.

dela[:bisect.bisect_right(a,6)]

You should note as well that bisect will only work on a sorted list.

Post a Comment for "Optimized Method Of Cutting/slicing Sorted Lists"