ภาพรวม
แปลง matrix (list of lists) ให้เป็น string เดียว โดยคั่น element ด้วย comma และแถวด้วย space/newline
ตัวอย่างโค้ด
my_list = [[1, 22, "python"], [22, "is", 1], ["great", 1, 91]]
print("The list is:", my_list)
# ใช้ join สองชั้น
row_sep = " "
col_sep = ","
my_result = row_sep.join([
col_sep.join(str(elem) for elem in row)
for row in my_list
])
print("The result is:", my_result)
ผลลัพธ์
The list is: [[1, 22, 'python'], [22, 'is', 1], ['great', 1, 91]]
The result is: 1,22,python 22,is,1 great,1,91
รูปแบบอื่นๆ
# ใช้ newline แทน space
row_sep = "\n"
# 1,22,python
# 22,is,1
# great,1,91
# ใช้ repr() แทน str() เพื่อให้ string มี quote
col_sep.join(repr(elem) for elem in row)
# 1,22,'python' 22,'is',1 'great',1,91
# Pretty print (สำหรับ debug)
import pprint
pprint.pprint(my_list)
CSV Format (มาตรฐาน)
import csv
import io
output = io.StringIO()
writer = csv.writer(output)
writer.writerows(my_list)
csv_string = output.getvalue()
print(csv_string)
# 1,22,python
# 22,is,1
# great,1,91
NumPy savetxt
import numpy as np
np.savetxt('matrix.csv', my_list, delimiter=',', fmt='%s')
# บันทึกเป็นไฟล์ CSV