使用 CSV 模块(*无 pandas*):如何打印 header 列中的行?
Using CSV module (*no pandas*): How to print the rows in a header column?
定义下面的函数 getColumn()
,它接受一个列名和 returns 该列中的数据作为字符串列表,以打印 header.[=16 中的项目=]
我的 getColumn(name)
函数失败并给出错误消息
unhashable type:list
import csv
from csv import DictReader
from collections import defaultdict
with open('training_set_features.csv') as new_csv_file:
new_csv_file = csv.DictReader(new_csv_file,fieldnames=headers)
data = list(new_csv_file)
column_names = list(data[0].keys())
print("List of column names : ", column_names)
# This part of my code is where I am stuck so it is incomplete
def getColumn(name):
empty_list=[]
column=dict[column_names]
for row in rows:
return
print(getColumn('doctor_recc_h1n1'))
将使用一种叫做“list comprehension”的东西来做需要的事情,它从每一行中提取指定列的数据,returns它。
请注意,因为 getColumn(name)
只传递了一个参数,即列名,所以它被迫使用全局变量 data
。如果将它 data
作为第二个参数传递会更好,以避免需要这样做,因为通常最好尽可能避免它们。
import csv
def getColumn(name):
return [row[name] for row in data]
with open('training_set_features.csv', newline='') as new_csv_file:
new_csv_file = csv.DictReader(new_csv_file)
data = list(new_csv_file)
column_names = list(data[0].keys())
print("List of column names : ", column_names)
print(getColumn('doctor_recc_h1n1'))
定义下面的函数 getColumn()
,它接受一个列名和 returns 该列中的数据作为字符串列表,以打印 header.[=16 中的项目=]
我的 getColumn(name)
函数失败并给出错误消息
unhashable type:list
import csv
from csv import DictReader
from collections import defaultdict
with open('training_set_features.csv') as new_csv_file:
new_csv_file = csv.DictReader(new_csv_file,fieldnames=headers)
data = list(new_csv_file)
column_names = list(data[0].keys())
print("List of column names : ", column_names)
# This part of my code is where I am stuck so it is incomplete
def getColumn(name):
empty_list=[]
column=dict[column_names]
for row in rows:
return
print(getColumn('doctor_recc_h1n1'))
将使用一种叫做“list comprehension”的东西来做需要的事情,它从每一行中提取指定列的数据,returns它。
请注意,因为 getColumn(name)
只传递了一个参数,即列名,所以它被迫使用全局变量 data
。如果将它 data
作为第二个参数传递会更好,以避免需要这样做,因为通常最好尽可能避免它们。
import csv
def getColumn(name):
return [row[name] for row in data]
with open('training_set_features.csv', newline='') as new_csv_file:
new_csv_file = csv.DictReader(new_csv_file)
data = list(new_csv_file)
column_names = list(data[0].keys())
print("List of column names : ", column_names)
print(getColumn('doctor_recc_h1n1'))