简体   繁体   English

将元组的字符串转换为元组

[英]Converting String of a tuple to a Tuple

If I have a string that looks like a tuple how can I make it into a tuple? 如果我有一个看起来像元组的字符串,我怎么能把它变成一个元组?

s = '(((3,),(4,2),(2,)),((1,),(2,4),(2,)))'

and I want to make it into a tuple that contains other tuples. 我想把它变成一个包含其他元组的元组。

t = tuple((((3,),(4,2),(2,)),((1,),(2,4),(2,))))

Doesn't work because it makes even the ( as a item in the tuple. 不起作用,因为它甚至使(作为元组中的项目)。

You need to use ast.literal_eval : 你需要使用ast.literal_eval

from ast import literal_eval
s = '(((3,),(4,2),(2,)),((1,),(2,4),(2,)))'

t = literal_eval(s)
print(t)
print(type(t))
(((3,), (4, 2), (2,)), ((1,), (2, 4), (2,)))
<class 'tuple'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM