猿问

从字符串解析元组?

假设我有一个字符串,该字符串的形式应该与元组相同,例如"(1,2,3,4,5)"。将其转换为实际元组的最简单方法是什么?我想做的一个例子是:


tup_string = "(1,2,3,4,5)"

tup = make_tuple(tup_string)

只是tuple()在字符串上运行会使整个事情变成一个大元组,而我想做的就是将字符串理解为一个元组。我知道我可以为此使用正则表达式,但是我希望有一种更便宜的方法。有想法吗?


桃花长相依
浏览 340回答 3
3回答

三国纷争

它已经存在!>>> from ast import literal_eval as make_tuple>>> make_tuple("(1,2,3,4,5)")(1, 2, 3, 4, 5)但是,请注意极端情况:>>> make_tuple("(1)")1>>> make_tuple("(1,)")(1,)如果您的输入格式与此处的Python不同,则您需要单独处理这种情况或使用诸如之类的其他方法tuple(int(x) for x in tup_string[1:-1].split(','))。

神不在的星期二

我们也可以自己解析它。假设我们有Python返回的元组,如下所示:((2, 'C/C++', 0, 'clang_cpp'), (3, 'Python相关', 0, 'python'))这是我们的方法首先,我们继续读取元组字符串中的字符,但存储最后一个左分号的位置以及遇到的分号数(我们可以将其称为左分号级,对于右分号也是如此),每当遇到右分号时,我们以下内容:从最后一个分号到当前右分号的一个子字符串。(在此子字符串中,不再有分号,我们只是将其用“,”分割成数组,假设新数组是M)然后,将其追加M到结果数组中,该数组将存储all M。第三,从原始字符串中删除我们提取的子字符串。最后,执行与步骤1相同的操作,直到左右分号的电平变为0。JavaScript代码如下所示:function parseTuple(t){&nbsp; &nbsp; var lc = "(";&nbsp; &nbsp; var rc = ")";&nbsp; &nbsp; var lc_level = 0;&nbsp; &nbsp; var rc_level = 0;&nbsp; &nbsp; var last_lc = 0;&nbsp; &nbsp; var last_rc = 0;&nbsp; &nbsp; var result = [];&nbsp; &nbsp; for(i=0;i<t.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; if(t[i] == lc){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lc_level++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; last_lc = i;&nbsp; &nbsp; &nbsp; &nbsp; }else if(t[i] == rc){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rc_level++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; last_rc = i;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if(rc_level == 1){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var substr = t.slice(last_lc+1,last_rc);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var data = substr.split(",");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.push(data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lc_level--;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rc_level--;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; t = t.slice(0,last_lc) + t.substring(last_rc+1);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if(lc_level == rc_level && lc_level==0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return result;}
随时随地看视频慕课网APP

相关分类

Python
我要回答