+ 1

How can I convert list values to integers in Python

I used import csv to convert a csv file to a list. However, the values were converted to string format. I want to convert them to integers. When I print the list, it shows up in this format: [ [‘1’],[‘2’],[‘3’] ] I suspect there’s an issue since it is in this format? Thanks for your help!

6th Apr 2018, 4:32 PM
Michael Patton
Michael Patton - avatar
6 RĂ©ponses
+ 2
lis=[ ['1'],['2'],['3'] ] intlis=[] for j in lis: for i in j: intlis.append(int(i)) print(intlis) print("`",ord('`')) print("'",ord("'")) #[ [‘1’],[‘2’],[‘3’] ] #note that your apstrophe is not the correct one
6th Apr 2018, 8:59 PM
Louis
Louis - avatar
+ 2
because your import loop imports elements as lists it makes a nested list with all elements as lists. Remove the import as lists and do it in values instead. for element in file: list.append(int(element))
6th Apr 2018, 5:19 PM
Markus Kaleton
Markus Kaleton - avatar
+ 1
As a beginner, i see this as a three lists inside a list. Maybe append an element from second/third sub-list into a first sub-list, then pull out the first sub-list as a separate list? That could be the moment for converting the elements into integers.
6th Apr 2018, 5:05 PM
Igor Matić
Igor Matić - avatar
+ 1
Thanks for the input. Based upon your feedback, I used a script to un nest the list.
6th Apr 2018, 7:53 PM
Michael Patton
Michael Patton - avatar
+ 1
Thanks Louis. That worked. Thanks everyone
6th Apr 2018, 9:01 PM
Michael Patton
Michael Patton - avatar
- 1
I would not use example from Louis if you can import it without that list nesting in the firat place since it takes unnecessary resources
7th Apr 2018, 12:06 AM
Markus Kaleton
Markus Kaleton - avatar