Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

Python: I have a string like this [3000,0.17],[3050,0.17],[3100,0.01] and would like to convert it to a list

Elements of the list should be: '[3000,0.17]','[3050,0.17]','[3100,0.01]' to my understanding I cannot use .split(','). Data is from a random json.file and I would like to have only the numbers.

Part of the file: "line": { "mbar":{'data': {'decX': 1, 'decY': 2, 'unX': 'mar', 'unY': 'min', 'poi': [[3000, 0.17], [3050, 0.17], [3100, 0.01]]}, 'svgurl': 'http://127.0.0.1:568/sg/save.min'} },

What I did so far:

enter code here
with open('Test.json') as json_file:  
data = json.load(json_file) 

test = data['line'] 
result = json.dumps(test)
result.replace("mbar":{'data': {'decX': 1, 'decY': 2, 'unX': 'mar', 'unY': 
'min', 'poi':'))
new_result = result[result.rfind("[["):]
new_result1 = new_result[:new_result.rfind("},")]
new_result2 = new_result1.replace('[[','[')
new_result3 = new_result2.replace(']]',']')

I end up with this [3000,0.17],[3050,0.17],[3100,0.01]

question from:https://stackoverflow.com/questions/65925019/python-i-have-a-string-like-this-3000-0-17-3050-0-17-3100-0-01-and-would

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Another approach is to USE split.

start_value = '[3000,0.17],[3050,0.17],[3100,0.01]'
output = []
tmp = ""
for e,s in enumerate(start_value.split(",")):
    if e % 2 == 0: # if e is even (even represents first value inside string list)
        tmp += s # append to tmp variable
    else:
        tmp += ","+s # for odd values (second part of string list), append comma with value because we are using comma as split delimiter
        output.append(tmp)
        tmp = ""
print(output)

Output will be >>> ['[3000,0.17]', '[3050,0.17]', '[3100,0.01]']


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...