让我们有一个带有行和列标题的 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:]]
...但它看起来不够 Pythonic。
这种自然操作有没有更简洁的方法?