将列表中的数据转换为正确的类型

时间:2017-10-30 05:07:40

标签: string python-3.x list loops

如何将列表中的数据转换为正确的类型,如果是整数,则intfloat如果不是整数,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]]

3 个答案:

答案 0 :(得分: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]
>

实际上,如果你需要一些强大且可扩展的东西,我会定义一个&#34;识别器&#34;每个类型的函数,除了默认的&#39; str&#39;,它返回转换结果或原始字符串(或抛出错误。)我会列出这些函数,从最具体到最少排序。 (例如,布尔识别器是非常具体的。)然后循环输入,尝试每个识别器功能,直到一个声明输入,使用其值作为结果并继续下一个输入。如果没有识别器声明输入,请保持原样。

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

答案 1 :(得分:1)

试用标准库中的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]

答案 2 :(得分:0)

试试这个:

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