Home > other >  adds only integers numbers of list
adds only integers numbers of list

Time:03-17

I tried lost of different commands but cant find how I can only count integers.

mix_list = [12, 3.3, -2, 'Flasche', 9, -4.1, 'Weg', 'auto', 2, 77, 0.5, 'X', 'Bla', 66.6, 22]
for i in mix_list:
    print(type(i),i)

CodePudding user response:

You could use a list comprehension to filter to only items which are integers, then counts that list items:

mix_list = [12, 3.3, -2, 'Flasche', 9, -4.1, 'Weg', 'auto', 2, 77, 0.5, 'X', 'Bla', 66.6, 22, True]
total = len([x for x in mix_list if type(x) is int])
print(total)

CodePudding user response:

Possible solution if the following:

mix_list = [12, 3.3, -2, 'Flasche', 9, -4.1, 'Weg', 'auto', 2, 77, 0.5, 'X', 'Bla', 66.6, 22, True]

counts = len([x for x in mix_list if isinstance(x, int) and not isinstance(x, bool)])

print(counts)

Prints

6

CodePudding user response:

mix_list = [12, 3.3, -2, 'Flasche', 9, -4.1, 'Weg', 'auto', 2, 77, 0.5, 'X', 'Bla', 66.6, 22]
m_int = []

for i in mix_list:
    if type(i) == int:
        m_int.append(i)
        print(i)

print(m_int)

The next option is faster, but the first one is more understandable.

m = [i for i in mix_list if type(i) == int]
print(m)
  • Related