gpt4 book ai didi

python - 缓存字符串列表转换为列表

转载 作者:太空宇宙 更新时间:2023-11-03 15:31:39 25 4
gpt4 key购买 nike

我缓存了包含单词的列表。我从缓存中以字符串类型下载列表。有谁知道如何将它们再次转换为列表?

第一个列表作为字符串

b"['cat', 'dog']"

我希望它处于这种阵型

['cat','dog']

作为列表。

我已经尝试过:

for lists in petlist:
x = lists.decode("utf-8")
x = x.replace('[','')
x = x.replace(']','')
resources = b.split (',')

if ',' in x:
x = x.split(',')
print(x)

有什么想法吗?

最佳答案

您可以使用ast.literal_eval计算包含有效 Python 文字的字符串。为了处理您的数据,我们需要将 bytes 对象解码为字符串。我们可以使用默认的UTF-8编码。

from ast import literal_eval

s = b"['cat', 'dog']"
a = literal_eval(s.decode())
print(a, type(a))

输出

['cat', 'dog'] <class 'list'>

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

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