gpt4 book ai didi

python - 如何将列表列表的字符串转换为列表?

转载 作者:行者123 更新时间:2023-12-02 02:15:42 25 4
gpt4 key购买 nike

我有这个文件,它是 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类型?

最佳答案

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

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

关于python - 如何将列表列表的字符串转换为列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67214204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com