python 将字符串转换为元组列表

mwyxok5s  于 2023-08-02  发布在  Python
关注(0)|答案(4)|浏览(118)

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

nfs0ujit

nfs0ujit1#

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

字符串

dgiusagp

dgiusagp2#

不带ast或eval:

def convert(in_str):
    result = []
    current_tuple = []
    for token in in_str.split(","):
        number = int(token.replace("(","").replace(")", ""))
        current_tuple.append(number)
        if ")" in token:
           result.append(tuple(current_tuple))
           current_tuple = []
    return result

字符串

ct2axkht

ct2axkht3#

无AST:

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

字符串

nwlqm0z1

nwlqm0z14#

只是为了完整:soulcheck的解决方案,它满足了原始海报的要求,以避免ast.literal_eval:

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

字符串

相关问题