Count how many values in a list that satisfy certain condition

前端 未结 7 1575
醉话见心
醉话见心 2021-01-11 13:50

I have the following list,

mylist = [\'0.976850566018849\',
 \'1.01711066941038\',
 \'0.95545901267938\',
 \'1.13665822176679\',
 \'1.21770587184811\',
 \'1.         


        
7条回答
  •  醉酒成梦
    2021-01-11 13:55

    You can use numpy or pandas, though for such a simple computation they would be much slower than the alternatives mentioned above.

    Using numpy,

    import numpy as np
    arr=np.array(mylist).astype(float)
    print len(arr[arr>=1.3])
    

    Using pandas,

    import pandas as pd
    s=pd.Series(mylist).astype(float)
    print len(s[s>=1.3])
    

    Alternatively,

    (pd.Series(l).astype(float)>=1.3).value_counts()[True]
    

    For performance, the fastest solution seems to be

    In [51]: %timeit sum(1 for x in mylist if float(x) >= 1.3)
    100000 loops, best of 3: 8.72 µs per loop
    

提交回复
热议问题