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

Lấy độ dài của list of lists trong Python

Dùng nested loop đếm số element trong mỗi sublist.

Ví dụ

>>> a = [[1, 2, 3], [4, 5, 6]]
>>> c = 0
>>> for x in a:
...     for y in x:
...         c += 1
>>> c
6

Cách ngắn gọn hơn

# Sum của độ dài các sublist
total = sum(len(sublist) for sublist in a)
print(total)  # 6

# Hoặc flatten rồi len
total = len([item for sublist in a for item in sublist])