python計算數組中對象出現的次數而且按照字典輸出

解決的問題如題,若是對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)

此時的輸出結果以下:spa

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

若是對python列表瞭解的多的話,可使用如下代碼解決問題,且時間複雜度下降。代碼以下:blog

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);

輸出的結果以下:it

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

相關文章
相關標籤/搜索