Get the first item from an iterable that matches a condition

前端 未结 13 2262
感情败类
感情败类 2020-11-22 04:43

I would like to get the first item from a list matching a condition. It\'s important that the resulting method not process the entire list, which could be quite large. For e

13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 05:17

    You could also use the argwhere function in Numpy. For example:

    i) Find the first "l" in "helloworld":

    import numpy as np
    l = list("helloworld") # Create list
    i = np.argwhere(np.array(l)=="l") # i = array([[2],[3],[8]])
    index_of_first = i.min()
    

    ii) Find first random number > 0.1

    import numpy as np
    r = np.random.rand(50) # Create random numbers
    i = np.argwhere(r>0.1)
    index_of_first = i.min()
    

    iii) Find the last random number > 0.1

    import numpy as np
    r = np.random.rand(50) # Create random numbers
    i = np.argwhere(r>0.1)
    index_of_last = i.max()
    

提交回复
热议问题