Reputation: 11
I want the strings converted into integer. tried doing it this way but for some reason it doesn't work
newList = []
myList = [['1', '2'], ['3', '4'], ['5', '6']]
for i in range (len(myList)):
for j in i:
b = int(myList[i][j])
newList.append(b)
print(newList)
I want the outcome to look like this:
[[1, 2], [3, 4], [5, 6]]
Upvotes: 1
Views: 70
Reputation: 4043
While i would use one of the solutions given by other members, here one simple one using numpy
:
import numpy
myList = [['1', '2'], ['3', '4'], ['5', '6']]
newlist = numpy.array( myList, dtype=int )
Memory wise probably not the best, but quite good readability. Though, at the end it is not a list, but a numpy array.
Upvotes: 0
Reputation: 608
you can also use map:
newList = [list(map(int, i)) for i in myList]
Actually, for this type of problem list comprehension and map
are somewhat interchangeable and the answer uses both.
Upvotes: 1
Reputation: 21
Answer above is very good, but I'd like to make code with your intention
newList = []
myList = [['1', '2'], ['3', '4'], ['5', '6']]
for i in range(len(myList)):
tempList=[]#we need tempList to make element list
#for j in i -> this makes error because for loop cant use in integer without range()
for j in range(len(myList[i])):
b = int(myList[i][j])
tempList.append(b)#make element list
newList.append(tempList)#append element list to newlist
print(newList)
I wish this can help you. Thanks :)
Upvotes: 2
Reputation: 1359
thats the way:
myList = [['1', '2'], ['3', '4'], ['5', '6']]
new_list = [[int(i) for i in e] for e in myList]
with for i in range(len(myList)):
you iterate through the index of the list, and not the elements itself. What you wanted to do:
newList = []
myList = [['1', '2'], ['3', '4'], ['5', '6']]
for i in myList:
stack = []
for j in i:
stack.append(int(j))
newList.append(stack)
print(newList)
Upvotes: 2