将python中混合数据类型对象中的数字转换为int / float,同时保持休息状态

问题描述 投票:1回答:1

我有一个列表如下:

    input_a= [['a','12','','23.5'],[12.3,'b2','-23.4',-32],[-25.4,'c']]

我想将此中的数字转换为数字以获得这样的输出

    output_a = [['a',12,'',23.5],[12.3,'b2',-23.4,-32],[-25.4,'c']]

我编写了以下代码以使其工作:

    def str_to_num(str_object=None):
      if not isinstance(str_object,str):
        return str_object
      try:
        x = int(str_object)
      except ValueError:
        try:
           x = float(str_object)
        except ValueError:
           x =str_object
      return x

    def getNumbers(num_object=None,return_container=None):
      a = return_container
      if isinstance(num_object,list):
        b = []
        for list_element in num_object:
           if isinstance(list_element,list):
              x = getNumbers(list_element,a)
           if isinstance(list_element,str):
              y = str_to_num(list_element)
              b += [y]
           if isinstance(list_element,int):
              y = list_element
              b += [y]
           if isinstance(list_element,float):
              y = list_element
              b += [y]
        a += [b]
      return return_container

    return_container = []
    output_a = getNumbers(input_a,return_container)[:-1]

这适用于(针对这种情况)。但是我有两个问题:1。如果有另一级别的列表嵌套,它就不能很好地工作。我想使它能够处理任何级别的嵌套。因此,如果

    input_b= [['a','12','','23.5',['15']],[12.3,'b2','-23.4',-32],[-25.4,'c']]

这给了

    output_b= [[-15],['a',12,'',23.5],[12.3,'b2',-23.4,-32],[-25.4,'c']]

这是错误的,因为[-15]应该嵌套在第一个子列表中。

  1. 代码非常冗长!!我相信必须有一个更简单的方法来处理这个问题。
python python-3.x
1个回答
2
投票

你遵循"Ask forgiveness not permission" - explain的传统,只是尝试转换。

input_b= [['a','12','','23.5',['15']],[12.3,'b2','-23.4',-32],[-25.4,'c']]

def parseEm(l):
    """Parses a list of mixed strings, strings of floats, strings of ints, ints and floats.
    Returns int where possible, float where possible else string as list elements."""
    def tryParse(elem):
        def asInt(e):
            """Tries to convert to int, else returns None"""
            try:
                return int(e)
            except:
                return None
        def asFloat(e):
            """Tries to convert to float, else returns None"""
            try:
                return float(e)
            except:
                return None        
        # if elem itself is a list, use list comp to get down it's elements
        if isinstance(elem,list):
            return [tryParse(q) for q in elem]

        # try to convert to int, else to float or return original value
        if isinstance(elem,str):
            a,b = asInt(elem),asFloat(elem)
            if a is not None:
                return a
            elif b is not None:
                return b

        return elem

        # this does not work, as interger 0 is considered false: 
        # return asInt(elem) or asFloat(elem) or elem

    # apply tryParse to all elements of the input list
    return [tryParse(k) for k in l]

print(parseEm(input_b))

输出:

[['a', 12, '', 23.5, [15]], [12, 'b2', -23.4, -32], [-25, 'c']]

但要小心,有些东西可以转换成你可能(不想)想要的浮动 - f.e。 ["NaN"]是一个有效的列表,其中包含1个浮点数。

© www.soinside.com 2019 - 2024. All rights reserved.