I got this value when retrieved from xls file → [1.5, 1.1, 0.85, 0.4] type = str.
I want this convert to list → [1.5, 1.1, 0.85, 0.4] type = list.
Any idea how i can do it…have tried many methods but could not get it right…thanks
a = "[1.5, 1.1, 0.85, 0.4]"
b = eval(a)
print(b, type(b))
[1.5, 1.1, 0.85, 0.4] <class 'list'>
that was fast…thanks man…
Be advised that eval
is a security risk; It will run anything you give it. Only run it on input data that you trust.
Here’s a simple, safe version:
value = "[1.5, 1.1, 0.85, 0.4]"
result = list(map(float, value[1:-1].split(",") ))
print(result)
Oh men…is there other way? I cant use eval…because the orignal creator have already use “eval” word as functions…thanks
Tell them to change it and not overwrite built in names.
In the meantime, you can use __builtin__.eval
instead.
Or just use @hauntsaninja’s safer solution.
>>> json.loads("[1.5, 1.1, 0.85, 0.4]")
[1.5, 1.1, 0.85, 0.4]
I got error → ‘list’ object is not callable
Sorry my bad…after i clear jupyter kernel it works…thank you so much
Use ast.literal_eval
, which is safe to use:
>>> import ast
>>> ast.literal_eval("[1.5, 1.1, 0.85, 0.4]")
[1.5, 1.1, 0.85, 0.4]
Though ast.literal_eval()
is much safer than eval()
it is not completely safe:
This function had been documented as “safe” in the past without defining what that meant. That was misleading. This is specifically designed not to execute Python code, unlike the more general
eval()
. There is no namespace, no name lookups, or ability to call out. But it is not free from attack: A relatively small input can lead to memory exhaustion or to C stack exhaustion, crashing the process. There is also the possibility for excessive CPU consumption denial of service on some inputs. Calling it on untrusted data is thus not recommended.Warning
It is possible to crash the Python interpreter due to stack depth limitations in Python’s AST compiler.
This is true, which is one of the reasons I would recommend json.loads
for this situation instead. Another reason is that, being a much much less capable parser, it is also significantly faster:
rosuav@sikorsky:~$ python3 -m timeit -s 'import json; x = "[1.5, 1.1, 0.85, 0.4]"' 'json.loads(x)'
200000 loops, best of 5: 1.34 usec per loop
rosuav@sikorsky:~$ python3 -m timeit -s 'import ast; x = "[1.5, 1.1, 0.85, 0.4]"' 'ast.literal_eval(x)'
50000 loops, best of 5: 8.73 usec per loop