0

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

import as
res = ast.literal_eval(lis) 

Can anyone tell me how to resolve this?

3 Answers 3

4

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]
Sign up to request clarification or add additional context in comments.

3 Comments

just updated the code @Tim. sorry for the delay
Check the updated answer. For future reference, please avoid changing your question after multiple users have given answers.
++ very good use of optional non-capture groups
0

You can try

[int(i) for i in lis.strip("[]").split(" ")]

Comments

0

You risk getting 1000 ways to do this.

This is a quick and easy way using only basic methods:

lis = '[1 2 3 4 5 77]'

elements = lis.replace('[','').replace(']','').split(' ')

my_ints = [int(e) for e in elements]

print(my_ints)

1 Comment

just updated the code...sorry for the delay

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.