Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert list of integers in string format to list of integers in python

I have a list which looks like below

lis = '[-3.56568247e-02 -3.31957154e-02\n  7.04742894e-02\n  7.32413381e-02\n  1.74463019e-02]' (string type)

‘\n’ is also there in the list.
I need to convert this to actual list of integers

lis = [-3.56568247e-02,-3.31957154e-02 ,7.04742894e-02 ,7.32413381e-02, 1.74463019e-02]  (list of integers)

I am doing the functionality, but it is failing

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import as
res = ast.literal_eval(lis) 

Can anyone tell me how to resolve this?

>Solution :

We can use re.findall along with a list comprehension:

lis = '[-3.56568247e-02 -3.31957154e-02  7.04742894e-02  7.32413381e-02\n  1.74463019e-02]'
output = [float(x) for x in re.findall(r'\d+(?:\.\d+)?(?:e[+-]\d+)?', lis)]
print(output)

# [0.0356568247, 0.0331957154, 0.0704742894, 0.0732413381, 0.0174463019]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading