在python中将嵌套列表的元素从字符串转换为整数

时间:2017-10-03 16:04:00

标签: python list data-structures

我有一个字符串格式的嵌套列表列表:

   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']]]]

是否有一种通用方法可以在不使用循环的情况下解决此问题?

4 个答案:

答案 0 :(得分:5)

递归可以很好地解决您的问题。

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]]]]

答案 1 :(得分:3)

如果你需要一个可能无限级别的嵌套,递归是你的朋友:

>>> 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]]]]

答案 2 :(得分:0)

int()是用于将字符串转换为整数值的Python标准内置函数。

l1 = [['1', '0', '3'],['4', '0', '6'],['0', '7', '8'],['0', '0', '0', '12']]
l2 = [map(int, x) for x in l1]
print(l2)

输出:

[[1, 0, 3], [4, 0, 6], [0, 7, 8], [0, 0, 0, 12]]

答案 3 :(得分:0)

如果您可以在外部列表中取消列出所有嵌套列表,可以通过以下方式完成:

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]