def read_csv(filename):
string_data = open(filename).read()
string_list = string_data.split("\n")[1:]
final_list = []
for row in string_list:
string_fields = row.split(",")
int_fields = []
for value in string_fields:
int_fields.append(value)
final_list.append(int_fields)
return final_list
cdc_list = read_csv("US_births_1994-2003_CDC_NCHS.csv")
cdc_list[0:3]
运行此代码时,我得到的结果如下:
[['1994', '1', '1', '6', '8096'], ['1994', '1', '2', '7', '7772'], ['1994', '1', '3', '1', '10142']]
但是我想要这样的结果:
[[1994, 1, 1, 6, 8096], [1994, 1, 2, 7, 7772], [1994, 1, 3, 1, 10142]]
您能帮我吗?
答案 0 :(得分:1)
以下列表推导会将cdc_list
的子列表中的字符串转换为整数:
[list(map(int, s)) for s in cdc_list]