+ 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!
6 Answers
+ 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
+ 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))
+ 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.
+ 1
Thanks for the input. Based upon your feedback, I used a script to un nest the list.
+ 1
Thanks Louis. That worked. Thanks everyone
- 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