计算python列表中元素的数量

时间:2015-01-15 00:41:02

标签: python list count

我需要编写一个python函数来计算列表中的所有元素,包括嵌套列表中的那些元素。

示例,len()内置函数,at_len()是我想要创建的函数:

len( [1, 2] )  ---> 2

at_len( [1, 2] ) ---> 2

len( [ [1, 2], 3 ] ) ---> 2

at_len( [ [1, 2], 3 ] ) ---> 3

len( [1, 2, 'three', [1, 2, 3, ['a', 'b'] ], 5] )  --> 5

at_len( [1, 2, 'three', [1, 2, 3, ['a', 'b'] ], 5] )  --> 9

我需要能够计算嵌套列表中的那些元素。这是我的代码,以及我得到的输出。

def at_len(element_list):
    count = 0
    for each_item in element_list:
            if isinstance(each_item, list):
                    at_len(each_item)
            else:
                    count = count + 1
    print(count)

输出:

at_len(['hello',1,2,'three',[1,'two',3]]) --> 3, 4 (should be 7)

at_len([1,2,[1,2,3]]) --> 3, 2 (should be 5)

我认为我很接近,但由于某种原因,它打印出两个计数而不是将它们加在一起以获得正确的总数。

1 个答案:

答案 0 :(得分:4)

at_len(each_item)替换为count += at_len(each_item),然后返回count(而不是打印)。

由于递归调用,它打印了两次。 print命令在函数内。另请注意,总数被赋予一个值但从未使用过。而是将其作为

def at_len(element_list):
    count = 0
    for each_item in element_list:
            if isinstance(each_item, list):
                    count += at_len(each_item)
            else:
                    count += 1
    return count

然后将其称为:

print(at_len(yourlist))
相关问题