เมื่อต้องการแปลงสตริงเป็นเมทริกซ์ (ลิสต์ของลิสต์) ที่มี K ตัวอักษรต่อแถว สามารถใช้ฟังก์ชันที่มี list comprehension และ list slicing ได้
ตัวอย่าง
def convert_to_matrix(my_string, my_key):
temp = [my_string[index: index + my_key] for index in range(0, len(my_string), my_key)]
my_result = [list(element) for element in temp]
print(my_result)
my_string = 'Python is fun'
print("The string is :")
print(my_string)
K = 7
print("The value of K is :")
print(K)
print("The result is :")
convert_to_matrix(my_string, K)
ผลลัพธ์
The string is : Python is fun The value of K is : 7 The result is : [['P', 'y', 't', 'h', 'o', 'n', ' '], ['i', 's', ' ', 'f', 'u', 'n']]
คำอธิบาย
กำหนดฟังก์ชัน
convert_to_matrixรับสตริงและ K (จำนวนตัวอักษรต่อแถว)ใช้ list comprehension ตัดสตริงทุก K ตัวอักษร (
my_string[index:index+my_key]) ได้ลิสต์สตริงย่อยแปลงแต่ละสตริงย่อยเป็นลิสต์ตัวอักษรด้วย
list(element)เรียกใช้ฟังก์ชันพร้อมแสดงผล