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

2

4 Answers 4

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]]
Sign up to request clarification or add additional context in comments.

4 Comments

[list(map(int, elem.split(' '))) for lstt in lst for elem in lstt] This is what map is for.
YW! Glad to have helped u!
@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.
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.
1
raw = [['1 2 3'], ['4 5 6'], ['7 8 9']]
data = [[int(i) for i in x[0].split(' ')] for x in raw]   

Comments

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)

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.