从字符串中提取列表

5

我正在使用Python,并且遇到从字符串中提取特定列表对象的问题。

这是我的一个包含列表对象的字符串:

input = "[[1,2,3],[c,4,r]]"

我需要类似于这样的输出。
output = [[1,2,3],[c,4,r]]

有没有办法做到这一点?

请注意,如果cr没有用引号括起来,ast.literal_eval将产生错误。 - rafaelc
5个回答

6
请使用ast.literal_eval进行操作:
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
   import ast
   input = "[[1,2,3],['c',4,'r']]"
   output = ast.literal_eval(input)
   output
=> [[1, 2, 3], ['c', 4, 'r']]

如果你的实际意思是希望cr只是变量cr的当前值,而不是字面值'c''r',那么你需要使用eval函数,这个函数具有一定的不安全性,但是它的工作方式基本相同。

这也适用于Python 3.8 - mikey

2
如果ast.literal_eval不够用,而且cr是非平凡的数据对象需要解释,您可以考虑使用astevalhttps://github.com/newville/asteval)。它可以处理超出文本字符串的Python字符串的评估,包括它自己的符号表,并避免使用eval()时存在的许多已知漏洞。 asteval就像一个带有简单、平坦命名空间的沙盒式迷你解释器。您需要向asteval解释器添加cr的值,但以下是一个示例:
from asteval import Interpreter
aeval = Interpreter()
aeval('c = 299792458.0')   # speed of light?
aeval('r = c/(2*pi)')      # radius of a circle of circumference c?
                           # note that pi and many other numpy
                           # symbols and functions are built in
input_string = "[[1,2,3],[c,4,r]]"

out = aeval(input_string)
print(out)

这将提供

[[1, 2, 3], [299792458.0, 4, 47713451.59236942]]

或者,你可以直接使用Python设置c

aeval.symtable['c'] = 299792458.0

许多已知的不安全操作都被asteval拒绝执行,但它也可以做许多ast.literal_eval无法完成的操作。当然,如果您正在接受来自用户输入的代码,请非常小心。


0

使用 ast 模块的 literal_eval 方法来更安全地执行评估操作

import ast
input = "[[1,2,3],['c',4,'r']]"
output= ast.literal_eval(input)
print(output)
#[[1, 2, 3], ['c', 4, 'r']]

这段代码已在Python 3.6中测试过,甚至在2.7版本中也可以运行。


0

我使用 pandas 函数 'read_json' 来解释存储为字符串的数据结构。 在这个例子中,你可以使用 typ ='series' 将结构解释为 pandas series,然后再将其转换回列表:

input = "[[1,2,3],[4,5,6]]"
pd.read_json(input, typ = 'series').to_list()

然而,由于某些原因,它只能处理数字内容,而不能处理包含数字和字符的列表示例。


-2

不要使用 input 作为变量名,它是 Python 中的关键字:

你可以使用 numpy:

import numpy as np

user_input = "[[1,2,3],[c,4,r]]"

print(np.array(user_input))

输出:

[[1,2,3],[c,4,r]]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接