How to turn a list of strings into a list of lists (containing ints)
Question:
I want to turn lst = ['123', '456', '789']
into lst = [[1,2,3], [4,5,6], [7,8,9]]
.
I tried:
for i in range(len(lst)):
lst[i] = list(lst[i])
This produced lst = [['1','2','3'], ['4','5','6'], ['7','8','9']]
.
How can I turn those string numbers into integers?
Note: I can’t use map
.
Answers:
Here is the solution:
lst = [['123'],['456'],['789']]
ans = []
temp = []
for i in lst:
for j in i:
temp = list(j)
for k in range(len(temp)):
temp[k] = int(temp[k])
ans.append(temp)
print(ans)
# output - [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Well, here is a simple solution for your problem:
final_list = []
for i in lst:
tmp_list = []
text = str(i[0])
for c in text:
tmp_list.append(int(c))
final_list.append(tmp_list)
lst = ['123','456','789']
for i in range(len(lst)):
lst[i] = [int(x) for x in lst[i]]
List comprehension approach:
lst = ['123', '456', '789']
lst = [[int(i) for i in string_number] for string_number in lst]
I want to turn lst = ['123', '456', '789']
into lst = [[1,2,3], [4,5,6], [7,8,9]]
.
I tried:
for i in range(len(lst)):
lst[i] = list(lst[i])
This produced lst = [['1','2','3'], ['4','5','6'], ['7','8','9']]
.
How can I turn those string numbers into integers?
Note: I can’t use map
.
Here is the solution:
lst = [['123'],['456'],['789']]
ans = []
temp = []
for i in lst:
for j in i:
temp = list(j)
for k in range(len(temp)):
temp[k] = int(temp[k])
ans.append(temp)
print(ans)
# output - [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Well, here is a simple solution for your problem:
final_list = []
for i in lst:
tmp_list = []
text = str(i[0])
for c in text:
tmp_list.append(int(c))
final_list.append(tmp_list)
lst = ['123','456','789']
for i in range(len(lst)):
lst[i] = [int(x) for x in lst[i]]
List comprehension approach:
lst = ['123', '456', '789']
lst = [[int(i) for i in string_number] for string_number in lst]