Reputation: 2488
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]]
Upvotes: 5
Views: 12297
Reputation: 180391
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=',')]
Upvotes: 9