Converting a list of strings to a list in python

I have a line as shown below

val = '["10249/54","10249/147","10249/187","10249/252","10249/336"]'

I need to parse it and accept the values ​​after / and put in the list below

['54','147','187','252','336']

My code is :[a[a.index('/')+1:] for a in val[1:-1].split(',')]

Output :['54"', '147"', '187"', '252"', '336"']

It also has double quotes, which is not true. After i tried as below

c = []
for a in val[1:-1].split(','):
    tmp = a[1:-1]
    c.append(tmp[tmp.index('/')+1:])

Output:

['54', '147', '187', '252', '336']

Is there a better way to do this?

+4
source share
4 answers

You can do this in one line quite easily:

from ast import literal_eval
a = [i.split('/')[-1] for i in literal_eval(val)]
a
>>>['54', '147', '187', '252', '336']

literal_eval() converts your string to a literal list.

+2
source

Yes ... assuming each value has /, as your example, this is superior:

>>> from ast import literal_eval
>>>
>>> val = '["10249/54","10249/147","10249/187","10249/252","10249/336"]'
>>> [int(i.split('/')[1]) for i in literal_eval(val)]
[54, 147, 187, 252, 336]

* edited to insert a forgotten bracket

+2
source

!

.

import re

val = '["10249/54","10249/147","10249/187","10249/252","10249/336"]'

output = re.findall('/(\d+)', val) # returns a list of all strings that match the pattern

print(output)

: ['54', '147', '187', '252', '336']

re.findall . docs .

+2
source

You can try a jsonmodule to convert a string to a list

>>> import json
>>> val ='["10249/54","10249/147","10249/187","10249/252","10249/336"]'
>>> list(map(lambda x: x.split('/')[-1], json.loads(val)))
>>> ['54', '147', '187', '252', '336']
+1
source

Source: https://habr.com/ru/post/1696043/


All Articles