簡體   English   中英

如何將列表列表的字符串轉換為列表?

[英]How to convert string of list of list to list?

我有這個文件,它是 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)

Output:

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

你可以看到它仍然是str類型,我怎樣才能使它成為list類型?

將其視為 json 行,並根據需要將部分行替換為 json 文檔

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

最后,您可以使用ast將列表的表示形式轉換為列表 object,如下所示:

import ast
sample = ['[0, 21], [1, 4], [2, 5]', '[0, 3], [1, 1], [2, 2]']
result = []
for item in sample:
    result.append(list(ast.literal_eval(item)))

這是包含所需元素的result

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM