สมมติว่าเรามีรายการที่มีประโยคเล็ก ๆ เป็นองค์ประกอบ เรามีรายการอื่นที่มีคำบางคำที่ใช้ในประโยคนี้ของรายการแรก เราต้องการค้นหาว่าคำสองคำจากรายการที่สองมีอยู่ร่วมกันในบางประโยคของรายการแรกหรือไม่
มี append และ for loop
เราใช้ for loop with in condition เพื่อตรวจสอบว่ามีคำในรายการประโยคหรือไม่ จากนั้นเราใช้ฟังก์ชัน len เพื่อตรวจสอบว่าเราถึงจุดสิ้นสุดของรายการแล้วหรือไม่
ตัวอย่าง
list_sen = ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
list_wrd = ['Eggs', 'Fruits']
print("Given list of sentences: \n",list_sen)
print("Given 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) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given list of sentences: ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday'] Given list of words: ['Eggs', 'Fruits'] ['Eggs and Fruits on Wednesday']
พร้อมทุกอย่าง
ที่นี่เราออกแบบ for loop เพื่อตรวจสอบว่าคำเหล่านั้นมีอยู่ในรายการที่มีประโยคหรือไม่ จากนั้นจึงใช้ฟังก์ชันทั้งหมดเพื่อตรวจสอบว่าคำทั้งหมดมีอยู่ในประโยคหรือไม่
ตัวอย่าง
list_sen = ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
list_wrd = ['Eggs', 'Fruits']
print("Given list of sentences: \n",list_sen)
print("Given list of words: \n",list_wrd)
res = [all([k in s for k in list_wrd]) for s in list_sen]
print("\nThe sentence containing the words:")
print([list_sen[i] for i in range(0, len(res)) if res[i]]) การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
ผลลัพธ์
Given list of sentences: ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday'] Given list of words: ['Eggs', 'Fruits'] The sentence containing the words: ['Eggs and Fruits on Wednesday']
พร้อมแลมบ์ดาและแผนที่
เราสามารถใช้แนวทางที่คล้ายคลึงกันข้างต้นได้ แต่ด้วยฟังก์ชันแลมบ์ดาและแผนที่ เรายังใช้ฟังก์ชันแยกและตรวจสอบความพร้อมใช้งานของคำที่กำหนดทั้งหมดในรายการพร้อมประโยค ฟังก์ชันแผนที่ใช้เพื่อใช้ตรรกะนี้อีกครั้งและกับแต่ละองค์ประกอบของรายการ
ตัวอย่าง
list_sen = ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday']
list_wrd = ['Eggs', 'Fruits']
print("Given list of sentences: \n",list_sen)
print("Given list of words: \n",list_wrd)
res = list(map(lambda i: all(map(lambda j:j in i.split(),
list_wrd)), list_sen))
print("\nThe sentence containing the words:")
print([list_sen[i] for i in range(0, len(res)) if res[i]]) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given list of sentences: ['Eggs on Sunday', 'Fruits on Monday', 'Eggs and Fruits on Wednesday'] Given list of words: ['Eggs', 'Fruits'] The sentence containing the words: ['Eggs and Fruits on Wednesday']