或者,您可以只使用字符串操作,这在许多情况下比 RE 更简单、更快。
>>> s = "312(21.1) 378(25.5) 374(25.3) 157(10.6) 260(17.6) 1481(100) 125(28.1) 91(20.4) 94(21.1) 52(11.7) 83(18.7) 445(100) 50(28.4) 44(25) 29(16.5) 12(6.8) 41(23.3) 176(100)"
将其拆分为令牌
>>> tokens = s.split()
>>> tokens
['312(21.1)', '378(25.5)', '374(25.3)', '157(10.6)', '260(17.6)', '1481(100)', '125(28.1)', '91(20.4)', '94(21.1)', '52(11.7)', '83(18.7)', '445(100)', '50(28.4)', '44(25)', '29(16.5)', '12(6.8)', '41(23.3)', '176(100)']
最后删除')'
>>> intermediary1 = [ entry[:-1] for entry in tokens ]
>>> intermediary1
['312(21.1', '378(25.5', '374(25.3', '157(10.6', '260(17.6', '1481(100', '125(28.1', '91(20.4', '94(21.1', '52(11.7', '83(18.7', '445(100', '50(28.4', '44(25', '29(16.5', '12(6.8', '41(23.3', '176(100']
分成2个字符串
>>> intermediary2 = [ entry.split('(') for entry in intermediary1 ]
>>> intermediary2
[['312', '21.1'], ['378', '25.5'], ['374', '25.3'], ['157', '10.6'], ['260', '17.6'], ['1481', '100'], ['125', '28.1'], ['91', '20.4'], ['94', '21.1'], ['52', '11.7'], ['83', '18.7'], ['445', '100'], ['50', '28.4'], ['44', '25'], ['29', '16.5'], ['12', '6.8'], ['41', '23.3'], ['176', '100']]
转换为数字(整数、浮点数)
>>> numbers = [ ( int(num1), float(num2) ) for num1, num2 in intermediary2 ]
>>> numbers
[(312, 21.1), (378, 25.5), (374, 25.3), (157, 10.6), (260, 17.6), (1481, 100.0), (125, 28.1), (91, 20.4), (94, 21.1), (52, 11.7), (83, 18.7), (445, 100.0), (50, 28.4), (44, 25.0), (29, 16.5), (12, 6.8), (41, 23.3), (176, 100.0)]
或者以更短的方式使用列表理解:
>>> tokens = [ entry[:-1].split('(') for entry in s.split()]
>>> numbers = [ ( int(num1), float(num2) ) for num1, num2 in tokens ]
>>> numbers
[(312, 21.1), (378, 25.5), (374, 25.3), (157, 10.6), (260, 17.6), (1481, 100.0), (125, 28.1), (91, 20.4), (94, 21.1), (52, 11.7), (83, 18.7), (445, 100.0), (50, 28.4), (44, 25.0), (29, 16.5), (12, 6.8), (41, 23.3), (176, 100.0)]