简体   繁体   English

将字符串列表转换为python中的列表

[英]Convert string list to list in python

I have a string as below , 我有一个字符串如下,

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

I need to parse it and take the values after / and put into list as below 我需要解析它并在/之后取值并将其放入列表中,如下所示

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

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

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

It has double quotes also " which is wrong. 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 any better way to do this? 有没有更好的方法来做到这一点?

You can do it in one line using literal_eval : 你可以使用literal_eval在一行中完成:

from ast import literal_eval

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

print(a)

Output: 输出:

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

literal_eval() converts your string into a list, and then i.split('/')[-1] grabs what's after the slash. literal_eval()将您的字符串转换为列表,然后i.split('/')[-1]获取斜杠之后的内容。

Yeah ... assuming every value has a / like 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 *编辑插入遗忘的括号

Try using regular expressions! 尝试使用正则表达式!

You can do it in a single line this way. 你可以用这种方式一行完成。

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)

Result: ['54', '147', '187', '252', '336'] 结果: ['54', '147', '187', '252', '336']

re.findall generates a new list called with all the matches of the regexp. re.findall生成一个名为regexp的所有匹配项的新列表。 Check out the docs on regular expressions for more info on this topic. 有关此主题的更多信息,请查看正则表达式文档

You can try json module to convert the string to list 您可以尝试使用json模块将字符串转换为列表

>>> 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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