Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python: ตรวจสอบว่าสองลิสต์มีสมาชิกร่วมกันหรือไม่

ระหว่างการจัดการข้อมูลด้วยลิสต์ Python เราพบสถานการณ์ที่ต้องรู้ว่าสองลิสต์ต่างกันหมดหรือมีสมาชิกร่วมกัน สามารถตรวจสอบได้โดยเปรียบเทียบสมาชิกในสองลิสต์ด้วยวิธีด้านล่าง

ใช้ In

ในลูป for เราใช้เงื่อนไข in ตรวจสอบว่าสมาชิกอยู่ในลิสต์หรือไม่ เราขยายตรรกะนี้เพื่อเปรียบเทียบสมาชิกของลิสต์ โดยเลือกสมาชิกจากลิสต์แรกและตรวจสอบความมีอยู่ในลิสต์ที่สอง ดังนั้นเราจะมี nested for loop สำหรับการตรวจสอบนี้

ตัวอย่าง

# ประกาศลิสต์
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("\n")
print("Comparing list1 and list3:")
print(commonelems(list1, list3))
print("\n")
print("Comparing list3 and list4:")
print(commonelems(list3, list4))

การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้

ผลลัพธ์

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

ใช้ Sets

อีกวิธีหนึ่งคือใช้ sets Sets มีคอลเลกชันสมาชิกเฉพาะที่ไม่มีลำดับ เราแปลงลิสต์เป็นเซต แล้วสร้างเซตใหม่โดยรวมเซตที่กำหนด ถ้ามีสมาชิกร่วมกัน เซตใหม่จะไม่ว่าง

ตัวอย่าง

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

# ตรวจสอบสมาชิกร่วมในสองลิสต์
z = commonelem_set(list1, list2)
print(z)

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_any(list1, list2))

การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้

ผลลัพธ์

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

สรุป: การใช้ set และ operator & (intersection) เป็นวิธีที่เร็วที่สุดและ Pythonic ที่สุดสำหรับตรวจสอบสมาชิกร่วม