Optimized method of cutting/slicing sorted lists

前端 未结 5 652
無奈伤痛
無奈伤痛 2021-01-02 08:10

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:

相关标签:
5条回答
  • 2021-01-02 08:38

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

    >>> import bisect
    >>> a[bisect.bisect_left(a, 6):]
    [7, 9]
    
    0 讨论(0)
  • 2021-01-02 08:40

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

    0 讨论(0)
  • 2021-01-02 08:47

    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.

    0 讨论(0)
  • 2021-01-02 08:52

    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.

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

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

    0 讨论(0)
  • 2021-01-02 08:57

    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.

    0 讨论(0)
提交回复
热议问题