[英]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: 我想将所有嵌套列表中的所有元素转换为整数,在这种情况下使用循环内的map函数:
>>> 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 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]]]]
int() is the Python standard built-in function to convert a string into an integer value. 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)
output: 输出:
[[1, 0, 3], [4, 0, 6], [0, 7, 8], [0, 0, 0, 12]]
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.