Return list of items in list greater than some value

前端 未结 7 1824
故里飘歌
故里飘歌 2020-11-29 02:16

I have the following list

j=[4,5,6,7,1,3,7,5]

What\'s the simplest way to return [5,5,6,7,7] being the elements in j greater o

7条回答
  •  -上瘾入骨i
    2020-11-29 02:54

    In case you are considering using the numpy module, it makes this task very simple, as requested:

    import numpy as np
    
    j = np.array([4, 5, 6, 7, 1, 3, 7, 5])
    
    j2 = np.sort(j[j >= 5])
    

    The code inside of the brackets, j >= 5, produces a list of True or False values, which then serve as indices to select the desired values in j. Finally, we sort with the sort function built into numpy.

    Tested result (a numpy array):

    array([5, 5, 6, 7, 7])
    

提交回复
热议问题