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?
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]]]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With