计算完整类型的混合类型列表中的整数元素数量:

时间:2018-11-24 16:58:56

标签: python python-3.x

[“ 1”,1,“ abc”,123,124.6,['123',1,45],(1、2),3456,567] 如何计算???有谁可以帮助我?

2 个答案:

答案 0 :(得分:1)

您可以递归地做到这一点:

def count_ints(data):
    counter=0
    for element in data:
        if type(element) == list or type(element) == tuple:
            counter+=count_ints(element)
        elif type(element)==int:
            counter+=1
return counter

致电:

print(count_in`enter code here`ts(["1", 1, "abc", 123, 124.6, ['123', 1, 45], (1, 2), 3456, 567]))

输出:

8

答案 1 :(得分:0)

def count_int_recursive(obj):
    count = 0
    if isinstance(obj, int):
        return count + 1
    try:
        for i in obj:
            if not i == obj:
                count += count_int_recursive(i)
    except TypeError:
        return count

integer_elements = count_int_recursive(values)