将Python字符串转换为列表

参见英文答案 > Convert string to list. Python [string.split() acting weird]                                    2个
我有一个格式如下所示的列表:

>>> x = "[26, 25]"
>>> list(x)
['[', '2', '6', ',', ' ', '2', '5', ']']

如何转换为包含如下所示元素的列表:

>>> x
[25, 26]
使用 ast.literal_eval()

import ast

ast.literal_eval(x)

或使用json.loads()将其视为JSON:

import json

json.loads(x)

ast.literal_eval()将Python文字作为输入(因此Python源代码中的文本会给你一个值),json.loads()接受JSON输入.

演示:

>>> import ast, json
>>> x = "[26, 25]"
>>> ast.literal_eval(x)
[26, 25]
>>> json.loads(x)
[26, 25]

只有在输入字符串中有一个以上的整数列表时,两者之间的区别才会起作用; JSON字符串包含unicode,Python 2上的ast.literal_eval()无法正确解释,而JSON类型只是ast.literal_eval()支持的子集.

>>> x = '["List", "with", "strings", "including", "snowman", "\u2603"]'
>>> ast.literal_eval(x)
['List', 'with', 'strings', 'including', 'snowman', '\\u2603']
>>> json.loads(x)
[u'List', u'with', u'strings', u'including', u'snowman', u'\u2603']
>>> x = "(1, 2, 3, 'a tuple is Python syntax, not JSON')"
>>> ast.literal_eval(x)
(1, 2, 3, 'a tuple is Python syntax, not JSON')
>>> json.loads(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/decoder.py", line 383, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
相关文章
相关标签/搜索