Khi cần đếm số phần tử trước khi gặp tuple đầu tiên trong một nested tuple, có thể dùng enumerate() và isinstance().
enumerate() trả về cặp (index, value) khi duyệt.
isinstance(obj, tuple) kiểm tra đối tượng có phải tuple không.
Ví dụ
my_tuple = (7, 8, 11, 0, (3, 4, 3), (2, 22))
print(f"Tuple: {my_tuple}")
# Duyệt với enumerate, dừng khi gặp tuple
count = 0
for idx, elem in enumerate(my_tuple):
if isinstance(elem, tuple):
count = idx
break
else:
# Không break -> không tìm thấy tuple nào
count = len(my_tuple)
print(f"Số phần tử trước tuple đầu tiên: {count}")
# Chi tiết từng bước
print("\nChi tiết:")
for idx, elem in enumerate(my_tuple):
is_tup = isinstance(elem, tuple)
print(f" Index {idx}: {elem!r:15} -> isinstance tuple: {is_tup}")
if is_tup:
print(f" -> Dừng tại index {idx}")
break
Kết quả
Tuple: (7, 8, 11, 0, (3, 4, 3), (2, 22)) Số phần tử trước tuple đầu tiên: 4 Chi tiết: Index 0: 7 -> isinstance tuple: False Index 1: 8 -> isinstance tuple: False Index 2: 11 -> isinstance tuple: False Index 3: 0 -> isinstance tuple: False Index 4: (3, 4, 3) -> isinstance tuple: True -> Dừng tại index 4
Giải thích
- Tuple có 6 phần tử: 4 phần tử số (index 0-3) và 2 nested tuple (index 4, 5).
enumerate()cho index và giá trị.isinstance(elem, tuple)kiểm tra kiểu tuple.- Gặp tuple đầu tiên tại index 4 -> có 4 phần tử trước đó (index 0,1,2,3).
- Khối
elsecủaforchạy nếu khôngbreak(không tìm thấy tuple).
Cách ngắn gọn: next() với generator
# Tìm index đầu tiên là tuple first_tuple_idx = next((i for i, x in enumerate(my_tuple) if isinstance(x, tuple)), len(my_tuple)) print(first_tuple_idx) # 4 # Hoặc dùng list.index() với điều kiện (phức tạp hơn) # Không trực tiếp được vì index() tìm giá trị chính xác
Đếm phần tử trước kiểu dữ liệu bất kỳ
def count_before_type(seq, target_type):
"""Đếm phần tử trước phần tử đầu tiên có kiểu target_type."""
for i, x in enumerate(seq):
if isinstance(x, target_type):
return i
return len(seq)
print(count_before_type(my_tuple, tuple)) # 4
print(count_before_type(my_tuple, list)) # 6 (không có list)
print(count_before_type(my_tuple, int)) # 0 (phần tử đầu là int)
Ứng dụng: Phân tách header và data
# Dữ liệu: header (scalar) + data rows (tuple)
data = ('id', 'name', 'score', (1, 'Alice', 95), (2, 'Bob', 87))
header_count = count_before_type(data, tuple)
header = data[:header_count]
rows = data[header_count:]
print(f"Header: {header}") # ('id', 'name', 'score')
print(f"Rows: {rows}") # ((1, 'Alice', 95), (2, 'Bob', 87))