Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking each data type in a list and to sum any numbers in the list and print them

Tags:

python

I'm trying to check every data type in a list and if the list has a mix of data types then print out that the list is a mix and sum any numbers in the list. It should work for any list. Any ideas? This is what I have so far.

a = ["cats",4,"n",2,"the",3,"house"]
total = 0
for i in a:
   if isinstance(i , int) and isinstance(i, str):
     total = total + i
     print "This list has a mix of data types"
     print total
   else:
like image 750
Anthony Avatar asked Dec 02 '22 11:12

Anthony


2 Answers

a = ["cats",4,"n",2,"the",3,"house"]
if len(set([type(i) for i in a])) > 1:
    print("Mixed types")
total = sum([i for i in a if type(i)==int or type(i)==float])
print(total)

This results in:

Mixed types
9
like image 200
briancaffey Avatar answered Dec 05 '22 01:12

briancaffey


I think you can remember for the first element of list, and then check if the remains element in the list is the same type of first element.

total = 0
first_type = type(a[0])
data_mixed = False
if isinstance(a[0], int):
    total += a[0]

if len(a) > 1:
    for i in a[1:]:
        if not isinstance(i, first_type):
            data_mixed = True
            print("This list has a mix of data types")
        if isinstance(i, int):
            total += i

if not data_mixed:
    print("not a mix of data types")
like image 35
Ballack Avatar answered Dec 05 '22 01:12

Ballack