简体   繁体   中英

String to list when missing comma in string

I have kinda painted myself in corner by converting vectors fom a dataframe to str . My vectors now look like this [ -9.1676396 -171.8196878] . The problem is that they somehow lost the comma in the middle, used to be like this [ -9.1676396, -171.8196878] . Then, whenever I would need a list conversion I could do:

literal_eval('[ -9.1676396, -171.8196878]')

However this no longer works since I've lost the comma. My question is, how can I transform a string like this in a list? I also have to account for the fact that some may differ in spacing. Here is the type of edits I could have:

[ -9.1676396 -171.8196878 ]
[1.2904753 103.8520359]
[   21.2160437 -157.975203 ]

Doesn't look like you have a string anymore, Just an array.

I suggest you use regex

 import re

 pattern =  "/[\s" #replace spaces on outside of numbers if any
 replace = "" # i.e nothing
 re.sub(pattern, replace)

Then do the same thing again but regex pattern would be

 re.sub([0-9]*\s[0-9]* , ",")

If you have line like:

[ -9.1676396 -171.8196878 ]

It can be easily converted to list of floats by follow code:

[float(x) for x in '[ -9.1676396 -171.8196878]'.replace('[','').replace(']','').split()]

This code removes [ and ] symbols, splits line with space as separator and converts resulting string parts into floats.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM