You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将列表生成的字符串转换回原列表(table)

你可以通过以下两种方式实现转换,优先推荐第一种安全方案:

方案1:使用ast.literal_eval(生产环境可用)

该方法仅解析Python标准字面量结构,不会执行任意代码,完全规避了eval的代码注入风险,是官方推荐的字面量反序列化方案。
操作示例:

# 首先导入ast模块
import ast

# 你的原有操作
hello = ["hello", "world"]
hellostring = str(hello)

# 转换回原列表
recovered_hello = ast.literal_eval(hellostring)

验证转换结果:

print(recovered_hello == hello)  # 输出 True
print(type(recovered_hello))  # 输出 <class 'list'>

方案2:使用eval(仅测试环境临时使用,不推荐)

该方法虽然也能得到正确结果,但如果字符串来源不可控,会有严重的代码注入风险,禁止在生产环境使用。
操作示例:

recovered_hello = eval(hellostring)

内容的提问来源于stack exchange,提问作者Tomek Gamer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 03:15:00