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?
CodePudding user response:
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]
CodePudding user response:
You can try
[int(i) for i in lis.strip("[]").split(" ")]
CodePudding user response:
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)