Reputation: 65
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?
Upvotes: 4
Views: 3471
Reputation: 309
If you need a possibly unlimited level of nesting, recursion is your friend:
>>> def cast_list(x):
... if isinstance(x, list):
... return map(cast_list, x)
... else:
... return int(x)
...
>>> l1 = [['1', '0', '3'],['4', '0', '6'],['0', '7', '8'],['0', '0', '0', '12']]
>>> l2 = ['1','4',['7',['8']],['0','1']]
>>> l3 = ['0',['1','5'],['0','1',['8',['0','2']]]]
>>> cast_list(l1)
[[1, 0, 3], [4, 0, 6], [0, 7, 8], [0, 0, 0, 12]]
>>> cast_list(l2)
[1, 4, [7, [8]], [0, 1]]
>>> cast_list(l3)
[0, [1, 5], [0, 1, [8, [0, 2]]]]
Upvotes: 3
Reputation: 447
If you are fine with un-listing all the nested lists within the outer list, it could be done in the following manner:
output_list = []
def int_list(l):
for i in l:
if isinstance(i, list):
int_list(i)
else:
output_list.append(int(i))
return output_list
Output:
>>> int_list(['1','4',['7',['8']],['0','1']])
[1, 4, 7, 8, 0, 1]
>>> int_list(['0',['1','5'],['0','1',['8',['0','2']]]])
[1, 4, 7, 8, 0, 1, 0, 1, 5, 0, 1, 8, 0, 2]
>>> int_list([['1', '0', '3'],['4', '0', '6'],['0', '7', '8'],['0', '0', '0', '12']])
[1, 4, 7, 8, 0, 1, 0, 1, 5, 0, 1, 8, 0, 2, 1, 0, 3, 4, 0, 6, 0, 7, 8, 0, 0, 0, 12]
Upvotes: 0
Reputation: 210
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]]]]
Upvotes: 6
Reputation: 2338
int() is the Python standard built-in function to convert a string into an integer value.
l1 = [['1', '0', '3'],['4', '0', '6'],['0', '7', '8'],['0', '0', '0', '12']]
l2 = [map(int, x) for x in l1]
print(l2)
output:
[[1, 0, 3], [4, 0, 6], [0, 7, 8], [0, 0, 0, 12]]
Upvotes: 0