检查列表中的每种数据类型,并对列表中的任何数字求和并打印它们

时间:2018-01-22 02:46:06

标签: python

我正在尝试检查列表中的每个数据类型,如果列表中混合了数据类型,则打印出列表是混合并对列表中的任何数字求和。它适用于任何列表。有任何想法吗? 这是我到目前为止所做的。

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:

6 个答案:

答案 0 :(得分:6)

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)

这导致:

Mixed types
9

答案 1 :(得分:3)

我认为您可以记住列表的第一个元素,然后检查列表中的遗留元素是否与第一个元素的类型相同。

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")

答案 2 :(得分:2)

您可能想要使用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

答案 3 :(得分: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

答案 4 :(得分: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检查某个项目是属于某种类型还是属于多种类型之一。如果x为类型1或类型2,则isinstance(x, (type1,type2 ) )返回true。

然后过滤掉数字并使用sum函数。

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

print(isMixedType(a))
#prints True

print(mixedTypeSum(a)) 
#prints 9

答案 5 :(得分: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