Optimized method of cutting/slicing sorted lists

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

提交回复
热议问题