Import csv as List of List of Integers

10,236

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=',')]
Share:
10,236
cooldood3490
Author by

cooldood3490

I'm too cool for school.

Updated on June 15, 2022

Comments

  • cooldood3490
    cooldood3490 almost 2 years

    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]]