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:
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
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With