从字符串中获取列表

时间:2014-07-16 12:34:16

标签: python python-2.7

我将下面的字符串作为另一个进程的输出。我需要只获取字符串中的列表列表,即删除作为字符串末尾字符的以下0.466, 0.161 : 19.032

字符串:

route = '''[[(5371.0, 10558.0, {'volume': 8.627265, 'length': 0.17}), (14604.0, 71071.0, {'volume': 15.135287, 'length': 0.28})], [(68127, 68127.0, {'volume': 10.072853, 'length': 0.25}), (5706, 5706.0, {'volume': 27.82635, 'length': 0.25, })], 0.466, 0.161] : 19.032'''

我想要的输出是下面的列表

[[(5371.0, 10558.0, {'volume': 8.627265, 'length': 0.17}), (14604.0, 71071.0, {'volume': 15.135287, 'length': 0.28})],  [(68127, 68127.0, {'volume': 10.072853, 'length': 0.25}), (5706, 5706.0, {'volume': 27.82635, 'length': 0.25})]] 

我试过了:

result = []
for r in eval(route.split(":")[0]):
    if type(r) == type([]):
        result.append(r)
print result

我收到了这个错误:

Traceback (most recent call last):
  File "C:/Users/AMAMIFE/Desktop/obi/SO.py", line 419, in <module>
    for l in eval(route.split(":")[0]):
  File "<string>", line 1
    [[(5371.0, 10558.0, {'volume'
                                ^
SyntaxError: unexpected EOF while parsing

我可以帮助解决我的错误以及如何解决问题吗?

1 个答案:

答案 0 :(得分:4)

您应该使用ast.literal_eval,而不是evalbad practice)。

请注意,字符串中有多个冒号,其中一些是有效的语法。您只想在最后一个上进行拆分,因此请使用str.rsplit并将maxsplit设置为1

>>> from ast import literal_eval
>>> route = "[[(5371.0, 10558.0, {'volume': 8.627265, 'length': 0.17}), (14604.0, 71071.0, {'volume': 15.135287, 'length': 0.28})], [(68127, 68127.0, {'volume': 10.072853, 'length': 0.25}), (5706, 5706.0, {'volume': 27.82635, 'length': 0.25, })], 0.466, 0.161] : 19.032"
>>> literal_eval(route.rsplit(":", 1)[0])
[[(5371.0, 10558.0, {'volume': 8.627265, 'length': 0.17}), (14604.0, 71071.0, {'volume': 15.135287, 'length': 0.28})], [(68127, 68127.0, {'volume': 10.072853, 'length': 0.25}), (5706, 5706.0, {'volume': 27.82635, 'length': 0.25})], 0.466, 0.161]

由于您不想要列表中的最后两项,请使用切片将其删除:

>>> literal_eval(route.rsplit(":", 1)[0])[:-2]
[[(5371.0, 10558.0, {'volume': 8.627265, 'length': 0.17}), (14604.0, 71071.0, {'volume': 15.135287, 'length': 0.28})], [(68127, 68127.0, {'volume': 10.072853, 'length': 0.25}), (5706, 5706.0, {'volume': 27.82635, 'length': 0.25})]]