zoukankan      html  css  js  c++  java
  • 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}

  • 相关阅读:
    第一阶段各队建议
    解决死锁四大方式
    进程和线程区别
    windows 地址空间分配
    Linux下用户组、文件权限详解
    2016总结
    class内部处理
    c++ devived object model
    static
    reinterpret
  • 原文地址:https://www.cnblogs.com/yisuowushinian/p/4715586.html
Copyright © 2011-2022 走看看