【问题标题】:Convert data in a list to the correct type将列表中的数据转换为正确的类型
【发布时间】:2017-10-30 05:07:40
【问题描述】:

如何将列表中的数据转换为正确的类型,即 int 如果是整数,float 如果不是整数,bool 如果是真或假?

def clean_data(data: List[list]) -> None:
"""Convert each string in data to an int if and only if it represents a
whole number, a float if and only if it represents a number that is not a
whole number, True if and only if it is 'True', False if and only if it is
'False', and None if and only if it is either 'null' or the empty string.

>>> d = [['abc', '123', '45.6', 'True', 'False']]
>>> clean_data(d)
>>> d
[['abc', 123, 45.6, True, False]]

【问题讨论】:

    标签: string python-3.x list loops


    【解决方案1】:

    如果可以解决您的问题,您可以尝试一种简单的方法:

    def clean_data(data):
        return [item == 'True' if item in ['True', 'False'] else \
            int(item) if item.isdigit() else \
            None if item in ['null', ''] else \
            item if item.isalpha() else \
            float(item) for item in data]
    
    print(clean_data(['abc', '123', '45.6', 'True', 'False']))
    

    输出

    > python3 test.py
    ['abc', 123, 45.6, True, False]
    >
    

    实际上,如果您需要一些健壮和可扩展的东西,我会为每种类型定义一个“识别器”函数,除了默认的“str”,它要么返回转换结果,要么返回原始字符串(或引发错误。)我会列出这些功能,从最具体到最不具体的顺序排列它们。 (例如,布尔识别器是非常具体的。)然后循环输入,尝试每个识别器函数,直到有人声明输入,使用它的值作为结果并继续下一个输入。如果没有识别器声明输入,请保持原样。

    这样,如果您有新的东西要转换,您只需定义一个新函数来识别并转换它,然后将其添加到识别器函数列表中的适当位置。

    【讨论】:

      【解决方案2】:

      试用标准库中的ast 模块:

      def clean_data(xs):
          clean_xs = list()
          for x in xs:
              try:
                  converted_x = ast.literal_eval(x)
              except ValueError:
                  converted_x = x
      
              clean_xs.append(converted_x)
          return clean_xs
      

      这给了你

      > clean_data(["1", "a", "True"])
      [1, "a", True]
      

      【讨论】:

        【解决方案3】:

        试试这个:

        import ast
        
        
        def clean_data(l):
            l1 = []
            for l2 in l:
                l3 = []
                for e in l2:
                    try:
                        l3.append(ast.literal_eval(e))
                    except ValueError:
                        l3.append(e)
                l1.append(l3)
            return l1
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-10-13
          • 1970-01-01
          • 2012-05-14
          • 2014-01-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-10
          相关资源
          最近更新 更多