Optimized method of cutting/slicing sorted lists

前端 未结 5 651
無奈伤痛
無奈伤痛 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: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.

提交回复
热议问题