[英]converting a string to a list of tuples
我需要在 Python [(2,3,4),(1,6,7)]
字符串'(2,3,4),(1,6,7)'
转换为元组列表[(2,3,4),(1,6,7)]
。 我想在每个','
处拆分,然后使用 for 循环并将每个元组附加到一个空列表中。 但我不太确定该怎么做。 一个提示,有人吗?
>>> list(ast.literal_eval('(2,3,4),(1,6,7)'))
[(2, 3, 4), (1, 6, 7)]
没有 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
没有 ast:
>>> list(eval('(2,3,4),(1,6,7)'))
[(2, 3, 4), (1, 6, 7)]
只是为了完整性:soulcheck 的解决方案,它满足原始海报避免 ast.literal_eval 的要求:
def str2tupleList(s):
return eval( "[%s]" % s )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.