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

Question:

I have a list which looks like below

lis = '[-3.56568247e-02 -3.31957154e-02n  7.04742894e-02n  7.32413381e-02n  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?

Asked By: merkle

||

Answers:

You can try

[int(i) for i in lis.strip("[]").split(" ")]
Answered By: Juleaume

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

lis = '[-3.56568247e-02 -3.31957154e-02  7.04742894e-02  7.32413381e-02n  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]
Answered By: Tim Biegeleisen

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)
Answered By: AirSquid
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.