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

Python - Kiểm tra hai danh sách có phần tử chung

Khi thao tác dữ liệu với list Python, cần biết hai danh sách hoàn toàn khác nhau hay có phần tử chung. So sánh phần tử bằng các cách sau.

Dùng toán tử In

Vòng lặp for với mệnh đề in kiểm tra sự hiện diện. Lồng vòng lặp: lấy phần tử từ list 1, kiểm tra trong list 2.

Ví dụ

list1 = ['a', 4, '%', 'd', 'e']
list2 = [3, 'f', 6, 'd', 'e', 3]
list3 = [12, 3, 12, 15, 14, 15, 17]
list4 = [12, 42, 41, 12, 41, 12]

def commonelems(x, y):
    common = 0
    for value in x:
        if value in y:
            common = 1
    if not common:
        return "The lists have no common elements"
    else:
        return "The lists have common elements"

print("Comparing list1 and list2:")
print(commonelems(list1, list2))
print("\nComparing list1 and list3:")
print(commonelems(list1, list3))
print("\nComparing list3 and list4:")
print(commonelems(list3, list4))

Kết quả:

Comparing list1 and list2: The lists have common elements
Comparing list1 and list3: The lists have no common elements
Comparing list3 and list4: The lists have common elements

Dùng Set

Chuyển list thành set (tập hợp phần tử duy nhất). Giao hai set (&). Nếu giao không rỗng -> có phần tử chung.

Ví dụ

list1 = ['a', 4, '%', 'd', 'e']
list2 = [3, 'f', 6, 'd', 'e', 3]

def commonelem_set(z, x):
    one = set(z)
    two = set(x)
    if (one & two):
        return ("There are common elements in both lists:", one & two)
    else:
        return ("There are no common elements")

def commonelem_any(a, b):
    out = any(check in a for check in b)
    if out:
        return "The lists have common elements."
    else:
        return "The lists do not have common elements."

print(commonelem_set(list1, list2))
print(commonelem_any(list1, list2))

Kết quả:

('There are common elements in both lists:', {'d', 'e'})
The lists have common elements.