【问题标题】:Converting elements of list of nested lists from string to integer in python在python中将嵌套列表列表的元素从字符串转换为整数
【发布时间】:2017-10-03 16:03:59
【问题描述】:

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

   l1 = [['1', '0', '3'],['4', '0', '6'],['0', '7', '8'],['0', '0', '0', '12']]

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

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

有没有不使用循环来解决这个问题的通用方法?

【问题讨论】:

  • 您是否考虑过为此使用递归?

标签: python list data-structures


【解决方案1】:

递归将是解决问题的好方法。

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

【讨论】:

  • 谢谢 jabargas,你的递归函数解决了我的问题
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      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]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-04-03
        • 2016-02-08
        • 2017-08-21
        • 2021-11-25
        • 2018-05-09
        • 2020-07-12
        • 1970-01-01
        相关资源
        最近更新 更多