In Python, how do you convert strings to a list of lists to other types such as ints, floats, booleans, etc.?

When providing a list of data, I will be asked to convert the lines from the list to the appropriate type, for example, int if the string contains integers, or float if it does not contain an integer. But I ran into this problem when it converts the value but does not change the original value in the list.

For example, if given:

d = [['abc', '123', '45.6', 'True', 'False']]

It should look like this after the conversion:

[['abc', 123, 45.6, True, False]]

So far, I have tried to write a for loop and convert the values ​​this way, but as I mentioned, it does not change the original list:

for lst in data:
    for index in lst:
        if index.isdigit():
            index = int(index)
        elif not index.isdigit():
            index = float(index)

I am not sure how to fix this problem or if it has another way. Any help would be appreciated! Thank:)

+4
source share
3

, , . , enumerate, :

import ast

d = [['abc', '123', '45.6', 'True', 'False']]

for lst in d:
  for i, x in enumerate(lst):
    try:
        lst[i] = ast.literal_eval(x)
    except (ValueError, SyntaxError):
        lst[i] = x
print(d)
# [['abc', 123, 45.6, True, False]]

ast.literal_eval Python, ( ), (. EAFP).

, ( , , ), , , , ast.literal_eval .

+5

- . , . isdigit() , string digit, , float. True False , .

, , , .

all = [['abc', '123', '45.6', 'True', 'False']]

for d in all:
    for x,y in enumerate(d):
        if y == "True":
            d[x] = True
        if y == "False":
            d[x] = False

for d in all:
    for x,y in enumerate(d):
        try:
            if y.isdigit() == True:
                d[x] = int(y)
            else:
                d[x] = float(y)
        except:
            pass

;

['abc', 123, 45.6, True, False]

abc
<class 'str'>
123
<class 'int'>
45.6
<class 'float'>
True
<class 'bool'>
False
<class 'bool'>
+1

Try (without library):

data = [['abc', '123', '45.6', 'True', 'False']]


def isfloat(x):
    try:
        a = float(x)
    except ValueError:
        return False
    else:
        return True


def isint(x):
    try:
        a = float(x)
        b = int(a)
    except ValueError:
        return False
    else:
        return a == b


for counter1, box in enumerate(data):

    for counter2, items in enumerate(box):

        if isfloat(items) is True:
            data[counter1][counter2] = float(items)

        elif isint(items) is True:
            data[counter1][counter2] = float(items)

        elif items == "True":
            data[counter1][counter2] = True

        elif items == "False":
            data[counter1][counter2] = False

        else:
            pass

print(data)
0
source

Source: https://habr.com/ru/post/1688373/


All Articles