pythonは配列内の要素の出現回数を統計して並べ替えます

7128 ワード

lis = [12,34,456,12,34,66,223,12,5,66,12,23,66,12,66,5,456,12,66,34,5,34]

def test1():
    #    
    c = []
    for i in lis:
        if i not in c:
            c.append(i)
    #    ,      
    b = []
    for i in c:
        num = 0
        for j in range(len(lis)):
            if lis[j] == i:
                num += 1
        a = []
        a.append(i)
        a.append(num)
        b.append(a)
    #     ,           
    for i in range(len(b)):
        for j in range(i,len(b)):
            if b[i][1] < b[j][1]:
                temp = b[i]
                b[i] = b[j]
                b[j] = temp
    print(b)

def test2():
    # set    ,          
    b = []
    for i in list(set(lis)):
        num = 0
        for j in range(len(lis)):
            if lis[j] == i:
                num += 1
        a = []
        a.append(i)
        a.append(num)
        b.append(a)
    #     ,           
    for i in range(len(b)):
        for j in range(i,len(b)):
            if b[i][1] < b[j][1]:
                temp = b[i]
                b[i] = b[j]
                b[j] = temp
    print(b)

def test3():
    #         ,   key,   value,    
    a = {}
    for i in lis:
        if i in a:
            a[i] = a[i] + 1
        else:
            a[i] = 1
    #   sorted       
    b = sorted(a.items(),key=lambda item:item[1],reverse=True)
    print(b)

def test4():
    from  collections import Counter
    import operator
    #    
    a = dict(Counter(lis))
    #    
    b= sorted(a.items(), key=operator.itemgetter(1),reverse=True)
    print(b)

if __name__ == '__main__':
    test1()
    test2()
    test3()
    test4()

出力結果は次のとおりです.
[[12, 6], [66, 5], [34, 4], [5, 3], [456, 2], [223, 1], [23, 1]]
[[12, 6], [66, 5], [34, 4], [5, 3], [456, 2], [23, 1], [223, 1]]
[(12, 6), (66, 5), (34, 4), (5, 3), (456, 2), (23, 1), (223, 1)]
[(12, 6), (66, 5), (34, 4), (5, 3), (456, 2), (23, 1), (223, 1)]

これは面接の過程で出会った問題の解決方法で、まとめてみました.編集者は初心者で、絶えず勉強しなければなりません.