Convert string list of lists to integer in python

Viewed 1735

I have a dataset in a text file and I read it then split its lines and have created a list of lists like

[['1 2 3'], ['4 5 6'], ... , ['7 8 9']]

How can I convert this list to an integer list like this?

[[1,2,3],[4,5,6],...,[7,8,9]]

4 Answers

This should help you:

lst = [['1 2 3'], ['4 5 6'],['7 8 9']]
lst = [elem.split(' ') for lstt in lst for elem in lstt]
lst = [[int(num) for num in lstt[:]] for lstt in lst]

Output:

>>> lst
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
raw = [['1 2 3'], ['4 5 6'], ['7 8 9']]
data = [[int(i) for i in x[0].split(' ')] for x in raw]   
  1. Each element inside the big list, we need to make it String and replace the ' by the empty string then split with space so you can get the list of elements with string type but you need to convert it to integer.
list1 = [['1 2 3'], ['4 5 6']]
for i in range(len(list1)):
   list1[i] = [int(e) for e in " ".join(list1[i]).replace("\'","").split()]

print(list1)

I have written a basic code that converts a list of list containing string elements to int element , i hope the below code solves your problem

lst = [['1 2 3'], ['4 5 6'],['7 8 9']]
lst2 = [elem.split(' ') for lst_ele in lst for elem in lst_ele]
final_list = []
for lists in lst2:
    test_list = list(map(int, lists)) 
    final_list.append(test_list)
print(final_list)
Related