我有一个字符串格式的列表嵌套列表,如下所示:
l1 = [['1', '0', '3'],['4', '0', '6'],['0', '7', '8'],['0', '0', '0', '12']]
我想将所有嵌套列表中的所有元素都转换为整数,在这种情况下,可以在循环内使用map函数:
>>> for i in range(len(l1)): ... l1[i]=list(map(int,l1[i]))
问题是我有很多这样的列表,它们具有多层嵌套,例如:
l2 = ['1','4',['7',['8']],['0','1']] l3 = ['0',['1','5'],['0','1',['8',['0','2']]]]
有没有不使用循环即可解决此问题的通用方法?
递归可以很好地解决您的问题。
def convert_to_int(lists): return [int(el) if not isinstance(el,list) else convert_to_int(el) for el in lists]
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]]]]