讓我們有一個CSV錶行和列標題,例如:一個Python的方式與行和列標題閱讀CSV
, "Car", "Bike", "Boat", "Plane", "Shuttle"
"Red", 1, 7, 3, 0, 0
"Green", 5, 0, 0, 0, 0
"Blue", 1, 1, 4, 0, 1
我想行和列標題,即:
col_headers = ["Car", "Bike", "Boat", "Plane", "Shuttle"]
row_headers = ["Red", "Green", "Blue"]
data = [[1, 7, 3, 0, 0],
[5, 0, 0, 0, 0],
[1, 1, 4, 0, 1]]
我當然可以這樣做
import csv
with open("path/to/file.csv", "r") as f:
csvraw = list(csv.reader(f))
col_headers = csvraw[1][1:]
row_headers = [row[0] for row in csvraw[1:]]
data = [row[1:] for row in csvraw[1:]]
...但它並不符合Python不夠。
這種自然操作有更好的方法嗎?
什麼'csvraw'? – martineau
@martineau我的代碼有錯誤。 'csvraw = list(csv.reader(f))'。 –