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

Python – แปลง List เป็น Matrix โดยขนาดแถวเพิ่มขึ้นทีละ K

ภาพรวม

จาก list แปลงเป็น matrix (list of lists) โดยแถวแรกมี k elements, แถวที่สองมี 2k, แถวที่สามมี 3k, ... จนหมด list

ตัวอย่างโค้ด


my_list = [42, 45, 67, 89, 99, 10, 23, 12, 31, 43, 60, 1, 0]
my_key = 3

print("The list is:", my_list)
print("The value of key is:", my_key)

my_result = []
for i in range(len(my_list) // my_key):
    end = (i + 1) * my_key
    my_result.append(my_list[:end])

print("The resultant matrix is:", my_result)

ผลลัพธ์

The list is: [42, 45, 67, 89, 99, 10, 23, 12, 31, 43, 60, 1, 0]
The value of key is: 3
The resultant matrix is:
[[42, 45, 67],
 [42, 45, 67, 89, 99, 10],
 [42, 45, 67, 89, 99, 10, 23, 12, 31],
 [42, 45, 67, 89, 99, 10, 23, 12, 31, 43, 60, 1]]

คำอธิบาย

  • len=13, key=3 -> 13//3 = 4 iterations (index 0,1,2,3)
  • i=0: end=3 -> [:3] = 3 elements
  • i=1: end=6 -> [:6] = 6 elements
  • i=2: end=9 -> [:9] = 9 elements
  • i=3: end=12 -> [:12] = 12 elements
  • Element สุดท้าย (index 12, value 0) ถูกทิ้ง

รูปแบบอื่น: Non-overlapping Chunks

หากต้องการแบ่งเป็น chunks ต่อเนื่องไม่ซ้อนทับ (3, 3, 3, 3, 1):


chunks = [my_list[i:i+my_key] for i in range(0, len(my_list), my_key)]
# [[42,45,67], [89,99,10], [23,12,31], [43,60,1], [0]]

NumPy Version


import numpy as np
arr = np.array(my_list)
# Reshape ต้องมีขนาดหารลงตัว
arr[:12].reshape(4, 3)  # ใช้ 12 elements แรก