Bisher wurde das Listenelement mit einer for-Anweisung gedreht, um zu überprüfen, wie viele Elemente in der Liste enthalten sind, und die Kombination aus Element und Nummer wurde in dict festgelegt. Wenn Sie jedoch die collection.Counter-Klasse verwenden, können Sie sie in einer Zeile verarbeiten.
    a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
    b = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6]
    a_dict = dict()
    b_dict = dict()
    for item in a:
        if item in a_dict:
            a_dict[item] += 1
        else:
            a_dict[item] = 1
    for item in b:
        if item in b_dict:
            b_dict[item] += 1
        else:
            b_dict[item] = 1
    print(a_dict) #{1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
    print(b_dict) #{1: 1, 2: 2, 3: 3, 4: 4, 6: 6}
    from collections import Counter
    a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
    b = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6]
    a_counter = Counter(a)
    b_counter = Counter(b)
    print(a_counter) #Counter({5: 5, 4: 4, 3: 3, 2: 2, 1: 1})
    print(b_counter) #Counter({6: 6, 4: 4, 3: 3, 2: 2, 1: 1})
    from collections import Counter
    a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
    b = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6]
    a_counter = Counter(a)
    b_counter = Counter(b)
    print(a_counter + b_counter) #Counter({4: 8, 3: 6, 6: 6, 5: 5, 2: 4, 1: 2})
    print(a_counter - b_counter) #Counter({5: 5})
Recommended Posts