Count how much of an object type is in a Python list

If I have a list in python:

a = [1, 1.23, 'abc', 'ABC', 6.45, 2, 3, 4, 4.98] 

Is there an easy way to count the amount of the type of an object in a ? Something simpler than the following, but gives the same result:

 l = [i for i in a if type(a[i]) == int] print(len(l)) 

I hope I made it clear.

+5
source share
5 answers
 a = [1, 1.23, 'abc', 'ABC', 6.45, 2, 3, 4, 4.98] sum(isinstance(i, int) for i in a) 

which returns

 4 
+1
source

Use isinstance to perform type checks, and then sum booleans to get count ( True is 1, False is 0):

 sum(isinstance(x, int) for x in a) 
+10
source

There are many ways to do this.

Here is the one that uses the list of fast map () and C-speed list.count () , using them as intended:

 >>> a = [1, 1.23, 'abc', 'ABC', 6.45, 2, 3, 4, 4.98] >>> map(type, a).count(int) 4 

In Python 3, map () returns an iterator, so you need a little modification, list(map(type, a)).count(int) .

Other approaches using sum () and Counter () are also reasonable (readable and used for their intended purpose), but a bit slower.

+6
source

Another way:

 >>> a = [1, 1.23, 'abc', 'ABC', 6.45, 2, 3, 4, 4.98] >>> len(filter(lambda e: isinstance(e, int), a)) 4 

You should be aware that any approach that uses isinstance will consider True or False as int since bool is a subclass of int:

 >>> isinstance(False, int) True >>> type(False)==int False 

So, if the difference between int and bool matters, use type(whatever)==int .

0
source

Use Counter !

 from collections import Counter type_counts = Counter(type(x) for x in a) assert type_counts[int] == 4 assert type_counts[float] == 3 assert type_counts[str] == 2 

This will not help you if you want to read all types and subtypes of a certain type. For example, the basestring type basestring not appear in the results, and I cannot use the code above to count it.

0
source

Source: https://habr.com/ru/post/1200558/


All Articles