Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python – Lọc tuple chỉ chứa số nguyên (Filter Tuples with Integers)

Lọc ra các tuple trong danh sách mà mọi phần tử đều là số nguyên (int). Sử dụng vòng lặp, isinstance() và cờ boolean.

Mã nguồn


my_tuple = [(14, 25, "Python"), (5, 6), (3,), ("cool",)]
print("Danh sách tuple:", my_tuple)

my_result = []
for sub in my_tuple:
    temp = True
    for element in sub:
        if not isinstance(element, int):
            temp = False
            break
    if temp:
        my_result.append(sub)

print("Tuple toàn số nguyên:", my_result)

Kết quả

Danh sách tuple: [(14, 25, 'Python'), (5, 6), (3,), ('cool',)]
Tuple toàn số nguyên: [(5, 6), (3,)]

Giải thích

  • Duyệt từng tuple sub.
  • Duyệt từng element trong tuple.
  • isinstance(element, int) kiểm tra kiểu int.
  • Nếu tìm thấy phần tử không phải int → temp=False, break.
  • Sau vòng lặp trong, nếu temp vẫn True → append tuple vào kết quả.

Cách ngắn gọn (all + generator)


my_result = [t for t in my_tuple if all(isinstance(e, int) for e in t)]

Lưu ý về bool

isinstance(True, int) = True (bool subclass int). Nếu cần loại trừ bool:


all(type(e) is int for e in t)