Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of list, converting all strings to int, Python 3

I am trying to convert all elements of the small lists in the big list to integers, so it should look like this:

current list:
list = [['1','2','3'],['8','6','8'],['2','9','3'],['2','5','7'],['5','4','1'],['0','8','7']]


for e in list:
    for i in e:
        i = int(i)

new list:
list = [[1,2,3],[8,6,8],[2,9,3],[2,5,7],[5,4,1],[0,8,7]]

Could anyone tell me why doesn't this work and show me a method that does work? Thanks!

like image 957
ufiufi Avatar asked Dec 23 '22 18:12

ufiufi


1 Answers

You can use a nested list comprehension:

converted = [[int(num) for num in sub] for sub in lst]

I also renamed list to lst, because list is the name of the list type and not recommended to use for variable names.

like image 65
janos Avatar answered Jan 04 '23 00:01

janos