2

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]]

meee
  • 35
  • 8
  • 3
    Does this answer your question? [How to split a string of space separated numbers into integers?](https://stackoverflow.com/questions/6429638/how-to-split-a-string-of-space-separated-numbers-into-integers) – Lescurel Oct 28 '20 at 12:53
  • @meee Let me know, what do you think of my answer. Since I am deleting not useful answers of mine – Sivaram Rasathurai Nov 01 '20 at 02:49

4 Answers4

5

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]]
Sushil
  • 5,440
  • 1
  • 8
  • 26
  • 1
    `[list(map(int, elem.split(' '))) for lstt in lst for elem in lstt]` This is what map is for. – CJR Oct 28 '20 at 13:00
  • YW! Glad to have helped u! – Sushil Oct 28 '20 at 13:06
  • @Sushil It produces `[[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. – CJR Oct 28 '20 at 13:56
  • I was in a hurry, so I forgot to remove the `.split()` line XD. But yeah. That is another way of achieving the same output. – Sushil Oct 28 '20 at 14:01
1
raw = [['1 2 3'], ['4 5 6'], ['7 8 9']]
data = [[int(i) for i in x[0].split(' ')] for x in raw]   
N. P.
  • 503
  • 4
  • 12
0
  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)

Sivaram Rasathurai
  • 5,533
  • 3
  • 22
  • 45
0

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)
Sachin Rajput
  • 238
  • 7
  • 26