码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-08-09 20:11:36      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

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

 

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

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!