Fork me on GitHub

python计算数组中对象出现的次数并且按照字典输出

解决的问题如题,如果对Python不是很熟悉,解决的办法可能如下:

test_array=[1,2,3,1,2,3];

def count_object1(array):
    result_obj={}
    for item in test_array:
        count=0
        for item_t in test_array:
            if item is item_t :
                count+=1
        result_obj[item]=count
    return result_obj


if __name__ == '__main__':
    print count_object1(test_array)

此时的输出结果如下:

{1: 2, 2: 2, 3: 2}

如果对python列表了解的多的话,可以使用以下代码解决问题,且时间复杂度降低。代码如下:

test_array=[1,2,3,1,2,3];

def count_object(test_array):
    result_obj={}
    for item in test_array:
        result_obj[item]=test_array.count(item)
    return result_obj;

if __name__ == '__main__':
    print count_object(test_array);

输出的结果如下:

{1: 2, 2: 2, 3: 2}

 

posted @ 2015-08-09 18:21  zhiqiang21  阅读(585)  评论(0编辑  收藏  举报