Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting elements of list of nested lists from string to integer in python

I have a nested list of lists in string format as:

   l1 = [['1', '0', '3'],['4', '0', '6'],['0', '7', '8'],['0', '0', '0', '12']]

I want to convert all elements in all nested lists to integers, using a map function inside a loop works in this case:

>>> for i in range(len(l1)):
...     l1[i]=list(map(int,l1[i]))

Problem is I have many such lists with multiple levels of nesting like:

l2 = ['1','4',['7',['8']],['0','1']]
l3 = ['0',['1','5'],['0','1',['8',['0','2']]]]

Is there a generic way to solve this problem without using loops?

like image 413
Mohit Avatar asked Jan 03 '23 09:01

Mohit


1 Answers

Recursion would be a good solution to your problem.

def convert_to_int(lists):
  return [int(el) if not isinstance(el,list) else convert_to_int(el) for el in lists]
l2 = ['1','4',['7',['8']],['0','1']]  
l3 = ['0',['1','5'],['0','1',['8',['0','2']]]] 
convert_to_int(l2)
>>>[1, 4, [7, [8]], [0, 1]] 
convert_to_int(l3)
>>>[0, [1, 5], [0, 1, [8, [0, 2]]]]
like image 133
jabargas Avatar answered Jan 10 '23 22:01

jabargas