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

时间:2015-08-09 20:10:16   收藏:0   阅读:503

解决的问题如题,如果对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}

 

原文:http://www.cnblogs.com/yisuowushinian/p/4715586.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!