带有嵌套列表创建的Python CSV导入 [英] Python CSV import with nested list creation
问题描述
我正在尝试简单地将.csv导入Python.我已经阅读了许多文档,但是对于我一生来说,我不知道该怎么做.
I am trying to simply import a .csv into Python. I've read numerous documents but for the life of me I can't figure out how to do the following.
CSV格式如下
NYC,22,55
BOSTON,39,22
我正在尝试生成以下内容:{NYC = [22,55],BOSTON = [39,22]},以便可以为每个变量循环调用i [0]和i [1].
I'm trying to generate the following : {NYC = [22,55], BOSTON = [39,22]} so that I can call i[0] and i[1] in a loop for each variable.
我尝试过
import csv
input_file = csv.DictReader(open("C:\Python\Sandbox\longlat.csv"))
for row in input_file:
print(row)
哪个会打印我的变量,但我不知道在城市名称中嵌套两个数字值并生成我希望获得的列表是很热门的.
Which prints my variables, but I dont know hot to nest two numeric values within the city name and generate the list that im hoping to get.
感谢您的帮助,对于我的菜鸟问题,很抱歉-
Thanks for your help, sorry for my rookie question -
推荐答案
如果您不熟悉python理解,则可以使用以下使用for循环的代码:
If you are not familiar with python comprehensions, you can use the following code that uses a for loop:
import csv
with open('C:\Python\Sandbox\longlat.csv', 'r') as f:
reader = csv.reader(f)
result = {}
for row in reader:
result[row[0]] = row[1:]
如果您希望数字为字符串,或者希望它们为数字,则先前的代码可以使用:
The previous code works if you want the numbers to be string, if you want them to be numbers use:
import csv
with open('C:\Python\Sandbox\longlat.csv', 'r') as f:
reader = csv.reader(f)
result = {}
for row in reader:
result[row[0]] = [int(e) for i in row[1:]] # float instead of int is also valid
这篇关于带有嵌套列表创建的Python CSV导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!