ภาพรวม
ตรวจสอบว่าทุก digit ในทุกตัวเลขของ list อยู่ในชุด digits ที่อนุญาตเท่านั้น
ตัวอย่างโค้ด
my_list = [427, 789, 345, 122, 471, 124]
my_digits = [1, 4, 7, 2]
print("The list is:", my_list)
# รวม digits ที่อนุญาตเป็น string
allowed_digits = ''.join(str(d) for d in my_digits)
# รวมทุก digits ใน my_list เป็น string
all_digits = ''.join(str(x) for x in my_list)
my_result = all(ch in allowed_digits for ch in all_digits)
if my_result:
print("The list contains only the required digits")
else:
print("The list doesn't contain only the required digits")
ผลลัพธ์
The list is: [427, 789, 345, 122, 471, 124]
The list doesn't contain only the required digits
คำอธิบาย
- Allowed digits: {'1', '2', '4', '7'}
- All digits in list: 4,2,7, 7,8,9, 3,4,5, 1,2,2, 4,7,1, 1,2,4
- พบ 8, 9, 3, 5 ซึ่งไม่อยู่ใน allowed -> False
เวอร์ชันที่อ่านง่ายกว่า
allowed = set(str(d) for d in my_digits)
all_digits = set(''.join(str(x) for x in my_list))
my_result = all_digits.issubset(allowed)
# หรือ
my_result = all(set(str(x)).issubset(allowed) for x in my_list)
กรณีต้องการเช็คต่อ Number (ไม่ใช่ต่อ Digit)
# ตรวจสอบว่าแต่ละตัวเลขประกอบด้วย allowed digits เท่านั้น
my_result = all(set(str(x)).issubset(allowed) for x in my_list)
# ผลเหมือนกัน แต่ logic ชัดเจนกว่า: "ทุก number ต้อง valid"