您可以使用eval。我想它会是最短的。
>>> s = '(1,2,3,4,5),(5,4,3,2,1)'
>>> ts = eval(s)
>>> ts
((1, 2, 3, 4, 5), (5, 4, 3, 2, 1))
>>> tsp = [(el[0],el[-1]) for el in ts]
>>> tsp
[(1, 5), (5, 1)]
不过,使用eval不是一个好习惯。
另一种选择是使用re 模块解析字符串。
>>> a = re.findall('\([^)]*\)',s)
>>> a
['(1,2,3,4,5)', '(5,4,3,2,1)']
正则表达式模式的意思是:
\( #opening parenthesis
[^)]* #from 0 to infinite symbols different from )
\) #closing parenthesis
.
>>> b = [el.strip('()') for el in a]
>>> b
['1,2,3,4,5', '5,4,3,2,1']
>>> c = [el.split(',') for el in b]
>>> c
[['1', '2', '3', '4', '5'], ['5', '4', '3', '2', '1']]
>>> d = [tuple(int(el2) for el2 in el) for el in c]
>>> d
[(1, 2, 3, 4, 5), (5, 4, 3, 2, 1)]
此外,您还可以执行以下操作:
>>> [tuple(int(i) for i in el.strip('()').split(',')) for el in s.split('),(')]
[(1, 2, 3, 4, 5), (5, 4, 3, 2, 1)]
这种方法根本不需要模块。但它不是很健壮(如果输入字符串会有一些不一致,例如括号和逗号之间的空格...), (...,那么注释会起作用)。