[英]Converting a string of tuples to a list of tuples in Python
How can I convert "[(5, 2), (1,3), (4,5)]"
into a list of tuples [(5, 2), (1,3), (4,5)]
如何将
"[(5, 2), (1,3), (4,5)]"
转换为元组列表[(5, 2), (1,3), (4,5)]
5,2 [(5, 2), (1,3), (4,5)]
I am using planetlab
shell that does not support "import ast"
. 我正在使用不支持
"import ast"
planetlab
shell。 So I am unable to use it. 所以我无法使用它。
If ast.literal_eval
is unavailable, you can use the (unsafe!) eval
: 如果
ast.literal_eval
不可用,则可以使用(unsafe!) eval
:
>>> s = "[(5, 2), (1,3), (4,5)]"
>>> eval(s)
[(5, 2), (1, 3), (4, 5)]
However, you should really overthink your serialization format. 但是,您应该真正考虑一下序列化格式。 If you're transferring data between Python applications and need the distinction between tuples and lists, use pickle .
如果要在Python应用程序之间传输数据,并且需要元组和列表之间的区别,请使用pickle 。 Otherwise, use JSON .
否则,请使用JSON 。
If you don't trust the source of the string enough to use eval
, then use re
. 如果您对字符串源的信任度不足以使用
eval
,请使用re
。
import re
tuple_rx = re.compile("\((\d+),\s*(\d+)\)")
result = []
for match in tuple_rx.finditer("[(5, 2), (1,3), (4,5)]"):
result.append((int(match.group(1)), int(match.group(2))))
The code above is very straightforward and only works with 2-tuples of integers. 上面的代码非常简单,仅适用于2元组的整数。 If you want to parse more complex structures, you're better off with a proper parser.
如果要解析更复杂的结构,最好使用适当的解析器。
'join' replace following characters '()[] ' and creates string of comma separated numbers 'join'替换后面的字符'()[]',并创建由逗号分隔的数字字符串
5,2,1,3,4,5
'split' splits that string on ',' and creates list strings 'split'将字符串拆分为','并创建列表字符串
['5','2','1','3','4','5']
'iter' creates iterator that will go over list of elements 'iter'创建迭代器,该迭代器将遍历元素列表
and the last line uses a list comprehension using 'zip' to group together two numbers 最后一行使用列表推导,使用“ zip”将两个数字组合在一起
it = iter("".join(c for c in data if c not in "()[] ").split(","))
result = [(int(x), int(y)) for x, y in zip(it, it)]
>>> [(5, 2), (1, 3), (4, 5)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.