Home > Net >  Convert list with str elements to list with integer elements
Convert list with str elements to list with integer elements

Time:05-29

I am importing data from csv file to python with code below:

import csv

excel = open(r"C:\Users\JP Dayao\Desktop\Python\Constraints Study\sample.csv")

raw = csv.reader(excel)

for i in raw:

    print(i)
    
excel.close()

The output is below:

['21', '34', '25', '31', '27', '36', '24']

Desired output is:

[21, 34, 25, 31, 27, 36, 24]

Please help... thank you!

CodePudding user response:

I am assuming that your csv file has a line like 21,34,25,31,27,36,24. The csv file may contain multiple lines. So you can use list comprehension like this-

raw = csv.reader(excel)

print([[int(x) for x in line] for line in raw])

output for a sinle line csv file:

[[1, 2, 3, 4, 5, 6]]

This is a nested list comprehension. The first one ... for line in raw will loop over all lines in csv file and the second one int(x) for x in line will loop over every element in that line and convert it to int.

The solution provided by @MohitC doesn't work because in that solution (i.e. [int(x) for x in raw]), x is itself a list containing elements present in a line and int() will not work on list. That is why you need another list comprehension

CodePudding user response:

import csv

excel = open(r"C:\Users\JP Dayao\Desktop\Python\Constraints Study\sample.csv")
raw = csv.reader(excel)
raw_int = []

for i in raw:
    for j in i:
        raw_int.append(int(j))

print(raw_int)
excel.close()
  • Related