Checking each type of data in the list and summing up any numbers in the list and printing them

I am trying to check each data type in a list, and if there is a combination of data types in the list, then print out that the list is a mix and sums up any numbers in the list. It should work for any list. Any ideas? This is what I still have.

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:
+4
source share
6 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)

It leads to:

Mixed types
9
+6
source

I think you can recall the first element of the list and then check if the remainder element in the list is the same type of the 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")
+3
source

try/except:

a = ["cats",4,"n",2,"the",3,"house"]
total = 0
msg = None

for i in a:
    try:
        total += float(i)
    except ValueError:
        msg = 'This list has a mix of data types'

if msg:
    print(msg)
print(total)

This list has a mix of data types
9.0
+2

:

a = ["cats",4,"n",2,"the",3,"house"]
data_types = []
total = 0
for i in a:
    if type(i) not in data_types:
        data_types.append(type(i))
    if isinstance(i, int):
        total += i
if len(data_types) > 1:
    print("List has a mix data type of: {0}".format(', '.join([str(i) for i in data_types])))
if total > 0:
    print("The total of integer in the list is: {0}".format(total))

:

List has a mix data type of: <class 'str'>, <class 'int'>
The total of integer in the list is: 9
+2
def isMixedType(l):
    return any( type(l[i]) != type(l[i+1]) for i in range(len(l)-1) )

, , , , , . any, . any , .

def mixedTypeSum(l):
    numbers_only = ( x for x in l if isinstance(x,(int,float)))
    return sum(numbers_only)

isinstance, , . isinstance(x, (type1,type2 ) ) true, x, 1 2.

sum .

a = ["cats",4,"n",2,"the",3,"house"]

print(isMixedType(a))
#prints True

print(mixedTypeSum(a)) 
#prints 9
+2

collections.defaultdict :

from collections import defaultdict

def mixed_types(lst):
    d = defaultdict(list)

    for x in lst:
        d[type(x)].append(x)

    if len(d) > 1:
        print("Mixed types")

    print(sum(d[int] + d[float]))

:

>>> mixed_types(["cats",4,"n",2.0,"the",3,"house", 3.0])
Mixed types
12.0
>>> mixed_types(["cats",4,"n",2,"the",3,"house"])
Mixed types
9
>>> print(mixed_types([1, 2, 3]))
6
+2

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


All Articles