将Python字符串转换为列表 [英] Convert Python string to list
问题描述
我有一个列表,其格式如下所示:
I have a list formatted as shown here:
>>> x = "[26, 25]"
>>> list(x)
['[', '2', '6', ',', ' ', '2', '5', ']']
如何转换为包含如下所示元素的列表:
How do I convert to a list with elements as shown here:
>>> x
[25, 26]
推荐答案
使用 ast.literal_eval()
:
import ast
ast.literal_eval(x)
或使用 json.loads()
将其视为JSON :
or treat it as JSON, using json.loads()
:
import json
json.loads(x)
ast.literal_eval()
将Python文字作为输入(因此,在Python源代码中的文本将为您提供一个值),json.loads()
将JSON输入.
ast.literal_eval()
takes Python literals as input (so text that in Python source code would give you a value), json.loads()
takes JSON input.
演示:
>>> 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()
支持的一部分.
The difference between the two only comes into play when you have more than a list of integers in your input string; JSON strings contain unicode, which ast.literal_eval()
on Python 2 would not interpret correctly, and JSON types are only a subset of what ast.literal_eval()
supports.
>>> 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
这篇关于将Python字符串转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!