从列表的第一个元素中删除双引号

时间:2017-09-07 18:58:51

标签: python python-2.7

我想从此列表中删除双引号:

>>> a
["6/1, 0, 0, ['79', '80', '81', '82']"]

我尝试将list的第一个元素转换为list,这是一个字符串,但是dint work:

>>> a[0]
"6/1, 0, 0, ['79', '80', '81', '82']"

>>> list(a[0])
['6', '/', '1', ',', ' ', '0', ',', ' ', '0', ',', ' ', '[', "'", '7', '9', "'", ',', ' ', "'", '8', '0', "'", ',', ' ', "'", '8', '1', "'", ',', ' ', "'", '8', '2', "'", ']']

预期产出:

>>> a
[6/1, 0, 0, ['79', '80', '81', '82']]
                    or
>>> a
['6/1', '0', '0', ['79', '80', '81', '82']]

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:4)

这会将字符串评估为列表:

a = list(eval(a[0]))

[6, 0, 0, ['79', '80', '81', '82']]

如果你知道你的端口是6/1,你可以用这样的字符串替换它:

a = list(eval(a[0]))
a[0] = '6/1'

['6/1', 0, 0, ['79', '80', '81', '82']]

如果你的端口要改变,但你知道它将永远是第一个元素,你可以这样做:

a = list(eval("'" + a[0].split(',')[0] + "'" + "," + ','.join(a[0].split(',')[1:])))

['6/1', 0, 0, ['79', '80', '81', '82']]

或更清洁的版本:

l = a[0].split(',')
a = list(eval("'" + l[0] + "' ," + ','.join(l[1:])))

['6/1', 0, 0, ['79', '80', '81', '82']]

答案 1 :(得分:1)

x= ["6/1, 0, 0, ['79', '80', '81', '82']" ]
a=x[0].replace('\'','').split(', [')
finallist=a[0].split(',')
finallist.append(a[1].replace(']','').split(','))
print (finallist)

输出

['6/1', ' 0', ' 0', ['79', ' 80', ' 81', ' 82']]