如何将字符串列表中括号内的数字解析为负数(或带负号的字符串)。
示例
input
list1= ['abcd','(1,234)','Level-2 (2):','(31)%', 'others','(3,102.2)%']
output
['abcd',-1234,'Level-2 (2):','-31%', 'others','-3102.2%']应该解析只有括号内有数字的字符串或括号中带有逗号/点的数字,后面跟着百分比(%)号。其他字符串(如'Level-2 (2):' )不应被解析。
我试过了
translator = str.maketrans(dict.fromkeys('(),'))
['-'+(x.translate(translator)) for x in list1]但是输出是(每个元素都附加了一个- )
['-abcd', '-1234', '-Level-2 2:', '-31%', '-others', '-3102.2%']发布于 2019-05-29 09:32:16
您可以尝试使用re.sub,例如:
import re
list1 = ['abcd','(1,234)','Level-2 (2):','(31)%', 'others','(3,102.2)%']
res = [re.sub(r'^\(([\d+.,]+)\)(%?)$', r'-\1\2', el) for el in list1]
# ['abcd', '-1,234', 'Level-2 (2):', '-31%', 'others', '-3,102.2%']发布于 2019-05-29 09:26:31
尝试使用re.match
Ex:
import re
list1= ['abcd','(1,234)','Level-2 (2):','(31)%', 'others','(31.2)%']
result = []
for i in list1:
m = re.match(r"\((\d+[.,]?\d*)\)(%?)", i)
if m:
result.append("-" + m.group(1)+m.group(2))
else:
result.append(i)
print(result)输出:
['abcd', '-1,234', 'Level-2 (2):', '-31%', 'others', '-31.2%']按意见更新
import re
list1 = ['abcd','(1,234)','Level-2 (2):','(31)%', 'others','(3,102.2)%']
result = []
for i in list1:
m = re.match(r"\((\d+(?:,\d+)*(?:\.\d+)?)\)(%?)", i)
if m:
result.append("-" + m.group(1).replace(",", "")+m.group(2))
else:
result.append(i)
print(result)输出:
['abcd', '-1234', 'Level-2 (2):', '-31%', 'others', '-3102.2%']发布于 2019-05-29 09:53:01
如果您不需要将值转换为int或float,re.match和str.translate就应该这样做:
rx = re.compile('\([\d,.]+\)%?$')
tab = str.maketrans({i: None for i in '(),'})
output = ['-' + i.translate(tab) if rx.match(i) else i for i in list1]它规定:
['abcd', '-1234', 'Level-2 (2):', '-31%', 'others', '-3102.2%']https://stackoverflow.com/questions/56357093
复制相似问题