在Python中将嵌套列表列表的元素从字符串转换为整数 [英] Converting elements of list of nested lists from string to integer in python

查看:736
本文介绍了在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']]

在这种情况下,我想使用循环内的map函数将所有嵌套列表中的所有元素都转换为整数:

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

这篇关于在Python中将嵌套列表列表的元素从字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆