Home > database >  I have a list whose elements are all dictionaries, and I want to count the total number of elements
I have a list whose elements are all dictionaries, and I want to count the total number of elements

Time:01-06

I have a list like this:

my_list=[{'is_pass':True},{'is_pass':True},{'is_pass':False},{'is_pass':False},{'is_pass':True},{'is_pass':True}]

I want to calculate the total number of elements, the number of True, and the number of False.

The following method can get what I want, but I think python should have an easier way to calculate the number of True and False respectively.I tried count, Counter, but failed to achieve the purpose, who knows how to get it quickly?

total = len(my_dict)
true_flag = 0
false_flag = 0
for i in my_list:
    if i['is_pass'] == True:
        true_flag  = 1
    if i['is_pass'] == False:
        false_flag  = 1

CodePudding user response:

You could use the Counter class from the collections library. It's much easier and effective:

from collections import Counter

my_list=[{'is_pass':True},{'is_pass':True},{'is_pass':False},{'is_pass':False},{'is_pass':True},{'is_pass':True}]    

print(Counter(tok['is_pass'] for tok in my_list))

This returns you with:

Counter({True: 4, False: 2})

CodePudding user response:

Try the following:

true_flag = sum([1 for i in my_list if i["is_pass"])
false_flag = len(my_list) - true_flag
  • Related