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]]
raw = [['1 2 3'], ['4 5 6'], ['7 8 9']]
data = [[int(i) for i in x[0].split(' ')] for x in raw]
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)