สมมติว่าเรามี list ที่มีประโยคสั้นๆ เป็นสมาชิก อีก list หนึ่งมีคำบางคำที่ใช้ในประโยคของ list แรก เราต้องการทราบว่าคำสองคำจาก list ที่สองปรากฏร่วมกันในประโยคของ list แรกหรือไม่
ใช้ append และ for loop
ใช้ for loop กับเงื่อนไข in ตรวจสอบความมีอยู่ของคำใน list of sentences แล้วใช้ len() ตรวจสอบว่าถึงท้าย list แล้วหรือไม่
ตัวอย่าง
list_sen = ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
list_wrd = ['Eggs', 'Fruits']
print("List of sentences: \n", list_sen)
print("List of words: \n", list_wrd)
res = []
for x in list_sen:
k = [w for w in list_wrd if w in x]
if (len(k) == len(list_wrd)):
res.append(x)
print(res)
ผลลัพธ์
การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้ −
['Eggs and Fruits on Wednesday']
ใช้ all
ออกแบบ for loop ตรวจสอบคำใน list of sentences แล้วใช้ all() ยืนยันว่าคำทั้งหมดอยู่ในประโยค
ตัวอย่าง
list_sen = ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
list_wrd = ['Eggs', 'Fruits']
print("List of sentences: \n", list_sen)
print("List of words: \n", list_wrd)
res = [all([k in s for k in list_wrd]) for s in list_sen]
print("\nประโยคที่มีคำเหล่านั้น:")
print([list_sen[i] for i in range(0, len(res)) if res[i]])
ผลลัพธ์
การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้ −
['Eggs and Fruits on Wednesday']
ใช้ lambda และ map
ใช้แนวคิดคล้ายกันแต่กับ lambda และ map ใช้ split() และตรวจสอบคำทั้งหมด map() ใช้ apply logic นี้กับทุกสมาชิก
ตัวอย่าง
list_sen = ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
list_wrd = ['Eggs', 'Fruits']
print("List of sentences: \n", list_sen)
print("List of words: \n", list_wrd)
res = list(map(lambda i: all(map(lambda j: j in i.split(), list_wrd)), list_sen))
print("\nประโยคที่มีคำเหล่านั้น:")
print([list_sen[i] for i in range(0, len(res)) if res[i]])
ผลลัพธ์
การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้ −
['Eggs and Fruits on Wednesday']