Count how many values in a list that satisfy certain condition

前端 未结 7 1428
醉话见心
醉话见心 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:59

    I take compactness, you mentioned in the question, as shorter code. So, I present

    sum(float(num) >= 1.3 for num in mylist)
    

    This takes advantage of the fact that, in python True values are taken as 1 and False as 0. So, whenever float(num) >= 1.3 evaluates to Truthy, it will be 1 and if it fails, result would be 0. So, we add all the values together to get the total number of items which are greater than or equal to 1.3.

    You can check that like this

    True == 1
    # True
    True + True
    # 2
    False * 10
    # 0
    

提交回复
热议问题