ระหว่างการจัดการข้อมูลโดยใช้รายการ python เราพบสถานการณ์ที่เราจำเป็นต้องทราบว่ารายการสองรายการแตกต่างกันโดยสิ้นเชิงหรือมีองค์ประกอบที่เหมือนกัน สามารถพบได้โดยการเปรียบเทียบองค์ประกอบในทั้งสองรายการกับวิธีการด้านล่างที่อธิบาย
การใช้งานอิน
ใน for loop เราใช้ in clause เพื่อตรวจสอบว่ามีองค์ประกอบอยู่ในรายการหรือไม่ เราจะขยายตรรกะนี้เพื่อเปรียบเทียบองค์ประกอบของรายการโดยเลือกองค์ประกอบจากรายการแรกและตรวจสอบการมีอยู่ในรายการที่สอง ดังนั้นเราจะซ้อนลูปเพื่อทำการตรวจสอบนี้
ตัวอย่าง
#Declaring lists
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]
# In[23]:
#Defining function to check for common elements in two lists
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")
# In[24]:
#Checking two lists for 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
การใช้ชุด
อีกวิธีในการค้นหา ถ้าสองรายการมีองค์ประกอบร่วมกันคือการใช้ชุด ชุดมีคอลเล็กชั่นองค์ประกอบที่ไม่เหมือนใคร ดังนั้นเราจึงแปลงรายการเป็นชุดแล้วสร้างชุดใหม่โดยการรวมชุดที่กำหนด หากมีองค์ประกอบร่วมกัน ชุดใหม่จะไม่ว่างเปล่า
ตัวอย่าง
list1=['a',4,'%','d','e']
list2=[3,'f',6,'d','e',3]
# Defining function two check common elements in two lists by converting to sets
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")
# Checking common elements in two lists for
z = commonelem_set(list1, list2)
print(z)
def commonelem_any(a, b):
out = any(check in a for check in b)
# Checking condition
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.