Khi cần xóa các tuple rỗng (và các giá trị "falsy" khác) khỏi list, có thể dùng list comprehension với điều kiện truthiness.
Trong Python, các giá trị "falsy" bao gồm: () (tuple rỗng), [] (list rỗng), '' (chuỗi rỗng), 0, None, False.
Ví dụ
def remove_empty_tuples(seq):
"""Xóa tuple rỗng và các giá trị falsy khỏi sequence."""
return [item for item in seq if item]
# List chứa tuple rỗng, chuỗi rỗng, tuple có khoảng trắng, tuple hợp lệ, string
my_list = [(), (), '', (' ', ' '), (45, 67, 35, 66, 74, 89, 100), 'jane']
print(f"List gốc: {my_list}")
# Gọi hàm
filtered = remove_empty_tuples(my_list)
print(f"\nSau khi lọc: {filtered}")
# Chi tiết từng phần tử
print("\nPhân tích từng phần tử:")
for i, item in enumerate(my_list):
truthy = bool(item)
print(f" [{i}] {repr(item):25} -> bool: {truthy} -> {'Giữ' if truthy else 'Xóa'}")
Kết quả
List gốc: [(), (), '', (' ', ' '), (45, 67, 35, 66, 74, 89, 100), 'jane']
Sau khi lọc: [(' ', ' '), (45, 67, 35, 66, 74, 89, 100), 'jane']
Phân tích từng phần tử:
[0] () -> bool: False -> Xóa
[1] () -> bool: False -> Xóa
[2] '' -> bool: False -> Xóa
[3] (' ', ' ') -> bool: True -> Giữ
[4] (45, 67, 35, 66, 74, 89, 100) -> bool: True -> Giữ
[5] 'jane' -> bool: True -> Giữ
Giải thích
if itemtrong list comprehension sử dụng truth value testing.- Tuple rỗng
(), chuỗi rỗng''là falsy -> bị loại. - Tuple
(' ', ' ')chứa 2 khoảng trắng -> non-empty -> truthy -> GIỮ. - Tuple có phần tử số -> truthy -> GIỮ.
- String
'jane'-> truthy -> GIỮ.
Chỉ xóa tuple rỗng (giữ chuỗi rỗng, 0, False...)
def remove_only_empty_tuples(seq):
"""Chỉ xóa tuple rỗng (), giữ các giá trị falsy khác."""
return [item for item in seq if not (isinstance(item, tuple) and len(item) == 0)]
test = [(), [], '', 0, False, None, (1,), ('',), 'hello']
print(remove_only_empty_tuples(test))
# [[], '', 0, False, None, (1,), ('',), 'hello']
Xóa tuple rỗng LỒNG NHAU (nested)
def deep_remove_empty_tuples(obj):
"""Đệ quy xóa tuple rỗng trong cấu trúc lồng nhau."""
if isinstance(obj, tuple):
# Xử lý tuple: lọc phần tử, rồi đệ quy
cleaned = tuple(deep_remove_empty_tuples(x) for x in obj if x != ())
return cleaned if cleaned else () # Trả về () nếu kết quả rỗng
elif isinstance(obj, list):
return [deep_remove_empty_tuples(x) for x in obj if x != ()]
return obj
nested = (1, (), (2, (), 3), [], ((),))
print(deep_remove_empty_tuples(nested))
# (1, (2, 3), [])
Xóa in-place (sửa đổi list gốc)
my_list = [(), (1,), (), (2,)]
# Duyệt ngược để xóa an toàn
for i in range(len(my_list) - 1, -1, -1):
if my_list[i] == ():
del my_list[i]
print(my_list) # [(1,), (2,)]