Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีแปลง Python Tuple เป็นตารางสองมิติ

หากคุณมีไลบรารีตัวเลขอย่าง numpy คุณควรใช้เมธอด reshape เพื่อ reshape tuple ให้เป็น multidimensional array

ตัวอย่าง

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

ผลลัพธ์

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

ตัวอย่าง

หากคุณต้องการทำใน 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)

ผลลัพธ์

((1, 2, 3), (4, 5, 6), (7, 8, 9))