เมื่อจำเป็นต้องค้นหาสตริงในรายการ คุณสามารถใช้เงื่อนไข 'if' ง่ายๆ พร้อมกับตัวดำเนินการ 'in' ได้
ตัวอย่าง
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน
my_list = [4, 3.0, 'python', 'is', 'fun']
print("The list is :")
print(my_list)
key = 'fun'
print("The key is :")
print(key)
print("The result is :")
if key in my_list:
print("The key is present in the list")
else:
print("The key is not present in the list") ผลลัพธ์
The list is : [4, 3.0, 'python', 'is', 'fun'] The key is : fun The result is : The key is present in the list
คำอธิบาย
- รายการจำนวนเต็มและสตริงถูกกำหนดและแสดงบนคอนโซล
- ค่าสำหรับคีย์ถูกกำหนดและแสดงบนคอนโซล
- ใช้ลูป 'if' เพื่อตรวจสอบว่ามีคีย์อยู่ในรายการหรือไม่
- ถ้าใช่ ผลลัพธ์จะแสดงบนคอนโซล