-1

I have a string, which contains a list of real numbers, for example, '[0.0, 6.5, 3.0]'

How can I convert it to list of real numbers?

In my python program I read a csv file and there is a column with color triplets. When I get them, I can't work with them, because they aren't lists with real numbers. I tried to convert, but when I go through the list there is a mistake, because the point that separates the integer and fractional part is not a number.

    if j == 'color':
        color_triple = []
        triple = ''.join(lines[i][j])
        for i_ in range(1, len(triple)):
            index = i_
            while triple[index] != ',':
                color = ''
                color += triple[i_]
                index += 1
            color_triple.append(float(color))
            i_ = index

I want to have a list [0.0, 6.5, 3.0] and work with elements of list as they are float.

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388

2 Answers2

0

This works

string = '[5.0, 0.9, 0.4]'
arr = eval(string)

print(arr)

But the output is

[5.0, 0.90000000000000002,0.40000000000000002]

You would have to do some post processing

EDIT:

As @ThiefMaster suggested, you can use Abstract Syntax Trees.

import ast

string = "[5.0, 9.0, 0.3]"
arr = ast.literal_eval(string)

print(arr)

Output:

[5.0, 9.0, 0.3]

More info on ast:

ast.literal_eval(node_or_string) Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

Warning: It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler. Changed in version 3.2: Now allows bytes and set literals. source: https://docs.python.org/3/library/ast.html

marsnebulasoup
  • 2,030
  • 2
  • 10
  • 28
-1

This could be overkill, but what about processing that string with a regex pattern? Below code works for what I believe your usage would be.

import re

def main():
    pattern = r"\[([\d]*\.[\d]*), ([\d]*\.[\d]*), ([\d]*\.[\d]*)\]"
    string = "[0.0, 6.5, 3.0]"

    results = re.search(pattern, string)

    print(float(results.group(1)), float(results.group(2)), float(results.group(3)))

if __name__ == '__main__':
    main()
Andrew St P
  • 742
  • 1
  • 3
  • 12