将字符串转换为元组列表

时间:2011-12-13 14:35:52

标签: python string list

我需要将一个字符串'(2,3,4),(1,6,7)'转换为Python中的元组[(2,3,4),(1,6,7)]列表。 我想在每','分开,然后使用for循环并将每个元组追加到一个空列表。但我不太清楚该怎么做。 有提示,有人吗?

4 个答案:

答案 0 :(得分:8)

>>> list(ast.literal_eval('(2,3,4),(1,6,7)'))
[(2, 3, 4), (1, 6, 7)]

答案 1 :(得分:2)

为了完整性:灵魂检查的解决方案,它符合原始海报的要求,以避免ast.literal_eval:

def str2tupleList(s):
    return eval( "[%s]" % s )

答案 2 :(得分:2)

没有ast或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

答案 3 :(得分:-1)

没有ast:

>>> list(eval('(2,3,4),(1,6,7)'))
    [(2, 3, 4), (1, 6, 7)]