擅长:python、mysql、java
<p>您可以编写递归函数,从逗号之间的值构建元组,同时考虑括号分组:</p>
<p>例如:</p>
<pre><code>s1 = "( 'label', ( 1.0, 2.0, 3.0 ) )"
s2 = "( 'label', #75, #174, #196, 37 )"
def str2Tuple(s):
if "(" not in s and "," not in s:
try : value = int(s) if s.isdigit() else float(s)
except: value = s.strip("'")
return value
result = []
group,value = 0,""
for c in s+",":
if c == "," and group == 0:
result.append(str2Tuple(value.strip()))
value = "";continue
group -= c==")"
if group>0 or c not in "()": value += c
group += c=="("
return tuple(result) if len(result)>1 else result[0]
print(str2Tuple(s1)) # ('label', (1.0, 2.0, 3.0))
print(str2Tuple(s2)) # ('label', '#75', '#174', '#196', 37)
</code></pre>