将csv导入为整数列表的列表 [英] Import csv as List of List of Integers
本文介绍了将csv导入为整数列表的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下CSV档案
12,29,63,44
54,43,65, 34
我试图将其作为列表列表导入,以使每个索引都是整数。这是我到目前为止。
import csv
pre>
filename ='file.csv'
with open (p,delimiter =',')中的rec的列表(rec)(列表(rec))中的列表的列表
print my_list
>>> [['12','29','63','44'],['54','43','65','34']]
正如你所看到的,这将产生一个字符串列表的列表,而不是整数。如何以整数列表的列表导入CSV文件?像这样
>>> [[12,29,63,44],[54,43,65,34]]
解决方案地图到int:
my_list =用于csv.reader(p,delimiter =',') ]
[[12,29,63,44],[54,43,65,34]]
这相当于:
my_list = [[int(x)for x in rec ] for csv.reader(p,delimiter =',')]
I have the following CSV file
12,29,63,44 54,43,65,34
I'm trying to import it as a list of list such that each index is an integer. Here's what I have so far.
import csv filename = 'file.csv' with open(filename, 'rU') as p: #reads csv into a list of lists my_list = list(list(rec) for rec in csv.reader(p, delimiter=',')) print my_list >>> [['12','29','63','44'],['54','43','65','34']]
As you can see this produces a list of list of strings, not integers. How do I import the CSV file as a list of list of integers? like this
>>> [[12,29,63,44],[54,43,65,34]]
解决方案map to int:
my_list = [list(map(int,rec)) for rec in csv.reader(p, delimiter=',')] [[12, 29, 63, 44], [54, 43, 65, 34]]
Which is equivalent to:
my_list = [[int(x) for x in rec] for rec in csv.reader(p, delimiter=',')]
这篇关于将csv导入为整数列表的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文