Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting a string to a list of tuples

I need to convert a string, '(2,3,4),(1,6,7)' into a list of tuples [(2,3,4),(1,6,7)] in Python. I was thinking to split up at every ',' and then use a for loop and append each tuple to an empty list. But I am not quite sure how to do it. A hint, anyone?

like image 718
Linus Svendsson Avatar asked Dec 13 '11 14:12

Linus Svendsson


3 Answers

>>> list(ast.literal_eval('(2,3,4),(1,6,7)'))
[(2, 3, 4), (1, 6, 7)]
like image 188
Sven Marnach Avatar answered Oct 23 '22 03:10

Sven Marnach


Without ast or eval:

def convert(in_str):
    result = []
    current_tuple = []
    for token in result.split(","):
        number = int(token.replace("(","").replace(")", ""))
        current_tuple.append(number)
        if ")" in token:
           result.append(tuple(current_tuple))
           current_tuple = []
    return result
like image 21
jsbueno Avatar answered Oct 23 '22 03:10

jsbueno


Just for completeness: soulcheck's solution, which meets the original poster's requirement to avoid ast.literal_eval:

def str2tupleList(s):
    return eval( "[%s]" % s )
like image 41
Scott Hunter Avatar answered Oct 23 '22 01:10

Scott Hunter