0

我有一个看起来像列表的字符串:

activeStateString = "['11', '20', '0']"

我想将其定义为 Python 中的列表。我知道我可以开始过滤并将其分解并重建一个新列表,但随后我必须进入循环等。Python中有没有办法立即将该字符串从“字符串”提升为列表?所以一旦转换:

activeStateString -> activeStateList

我得到:

11

为了:

print activeStateList[0]

谢谢

(Python 2.6)

4

2 回答 2

5

用于ast.literal_eval()解释包含 Python 文字的字符串:

>>> import ast
>>> ast.literal_eval("['11', '20', '0']")
['11', '20', '0']

这更安全,eval()因为它会拒绝解释任何不是文字值的东西:

>>> eval("__import__('sys').version")
'2.7.5 (default, Oct 28 2013, 20:45:48) \n[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)]'
>>> ast.literal_eval("__import__('sys').version")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/ast.py", line 80, in literal_eval
    return _convert(node_or_string)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/ast.py", line 79, in _convert
    raise ValueError('malformed string')
ValueError: malformed string
于 2013-11-07T12:23:05.960 回答
2

使用ast.literal_eval

>>> import ast
>>> s = "['11', '20', '0']"
>>> lst = ast.literal_eval(s)
>>> lst
['11', '20', '0']

如果要将列表项转换为整数,请使用int()with或列表推导:map

>>> map(int, lst)
[11, 20, 0]

帮助ast.literal_eval

>>> help(ast.literal_eval)
Help on function literal_eval in module ast:

literal_eval(node_or_string)
    Safely evaluate an expression node or a string containing a Python
    expression.  The string or node provided may only consist of the following
    Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
    and None.
于 2013-11-07T12:22:54.310 回答