我如何完成这个功能?我只写了我的一部分

2024-04-20 05:19:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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]]
    >>> d = [['ab2'], ['-123'], ['False', '3.2']]
    >>> clean_data(d)
    >>> d
    [['ab2'], [-123], [False, 3.2]]
    """

    d = []
    for sublist in data:
        l1 = []
        if i.isalpha():
            l1.append(i)
        elif i.isdigit():
            l1.append(int(i))

Tags: andincleannonefalsetruel1number
1条回答
网友
1楼 · 发布于 2024-04-20 05:19:30

如果不想使用任何软件包,请尝试以下操作:

def clean_data(data):

    for index, datum in enumerate(data):

        split = datum.split(".")

        if datum.isdigit():

            data[index] = int(datum)

        elif len(split) == 2 and split[0].isdigit() and split[1].isdigit():

            data[index] = float(datum)

        elif datum == "True":

            data[index] = True

        elif datum == "False":

            data[index] = False

        elif datum == "null" or datum == "":

            data[index] = None

    return data

data = ["abc", "123", "45.6", "True", "False"]
print("Before:\t", data)

data = clean_data(data)
print("After:\t", data)

其输出如下:

Before:  ['abc', '123', '45.6', 'True', 'False']
After:   ['abc', 123, 45.6, True, False]

尽管less advisable,另一种可能的方法是使用内置的eval()函数:

def clean_data(data):

    for index, datum in enumerate(data):

        # None if and only if datum is either "null" or the empty string.
        if datum == "null" or datum == "":

            data[index] = None

        # Leave string "None" as string per if and only if requirement.
        elif datum != None:

            try:

                data[index] = eval(datum)

            except:

                pass

    return data

data = ["abc", "123", "45.6", "True", "False"]
print("Before:\t", data)

data = clean_data(data)
print("After:\t", data)

其输出相同。你知道吗

相关问题 更多 >