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

Chuyển Python Tuple thành bảng 2 chiều (2D table)

Nếu có numpy: dùng reshape().

Ví dụ numpy

import numpy
data = numpy.array(range(1, 10))
data.reshape([3, 3])
print(data)

Kết quả: 3x3 array.

Pure Python (list comprehension)

data = tuple(range(1, 10))
table = tuple(data[n:n+3] for n in range(0, len(data), 3))
print(table)

Kết quả: ((1, 2, 3), (4, 5, 6), (7, 8, 9))