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]]
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]]
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]]
[list(map(int, elem.split(' '))) for lstt in lst for elem in lstt] This is what map is for.[[1, 2, 3], [4, 5, 6], [7, 8, 9]] and you got something different because you were not running it on the original list but an already-processed list. The reason to use one-liners is to avoid multiple intermediate assignments that can lead to mistakes like that..split() line XD. But yeah. That is another way of achieving the same output.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)