首页 > 解决方案 > 如何将列表列表的字符串转换为列表?

问题描述

我有这个文件,它是 MapReduce 作业的结果,因此它具有key-value以下格式:

'null\t[0, [[0, 21], [1, 4], [2, 5]]]\n'
'null\t[1, [[0, 3], [1, 1], [2, 2]]]\n'

我想删除除此值列表的第二个元素之外的所有字符:

[[0, 21], [1, 4], [2, 5]]
[[0, 3], [1, 1], [2, 2]]

最后,将每个添加到一个列表中:

[[[0, 21], [1, 4], [2, 5]], [[0, 3], [1, 1], [2, 2]]]

这是我迄今为止的尝试:

with open(FILENAME) as f:
    content = f.readlines()

for line in content:
    # Just match all the chars upto "[[" then replace the matched chars with "["
    clean_line = re.sub(r'^.*?\[\[', '[', line)
    # And remove "\n" and the last 2 "]]" of the string
    clean_line = re.sub('[\n]', '', clean_line)[:-2]
    corpus.append(clean_line)

输出:

['[0, 21], [1, 4], [2, 5]', '[0, 3], [1, 1], [2, 2]']

你可以看到它仍然是str打字,我怎样才能让它list打字?

标签: pythonlist

解决方案


将其视为一行 json 并根据需要将部分行替换为 json 文档

import json
corpus = [json.loads(line.replace('null\t', '{"a":').replace("\n", "}"))["a"][1] for line in content]

推荐阅读