Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tìm phần tử chung của ba mảng đã sắp xếp bằng giao dictionary trong Python


Cho ba mảng, tìm các phần tử chung xuất hiện trong cả ba. Sử dụng Counter từ collections và phép giao dictionary (&).

Ví dụ minh họa

from collections import Counter
arrayA = ['Sun', 12, 14, 11, 34]
arrayB = [6, 12, 'Sun', 11]
arrayC = [19, 6, 20, 'Sun', 12, 67, 11]
arrayA = Counter(arrayA)
arrayB = Counter(arrayB)
arrayC = Counter(arrayC)
commonDict = dict(arrayA.items() & arrayB.items() & arrayC.items())
res = []
for key, val in commonDict.items():
    for _ in range(val):
        res.append(key)
print("Phần tử chung:", res)  # ['Sun', 11, 12]