将带括号的数字解析为负数

时间:2019-05-29 09:17:27

标签: python python-3.x list

我如何将字符串列表中带括号的数字解析为负数(或带负号的字符串)。

示例

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%']

4 个答案:

答案 0 :(得分:4)

您可以尝试使用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%']

答案 1 :(得分:2)

尝试使用re.match

例如:

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%']

答案 2 :(得分:1)

如果您不需要将值转换为int或float,则re.matchstr.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%']

答案 3 :(得分:0)

for item in list1:
    idx = list1.index(item)
    list1[idx] = '-' + list1[idx].replace('(','').replace(')','').replace(',','')

print (list1)

输出:

['-abcd', '-1234', '-Level-2 2:', '-31%', '-others', '-3102.2%']

或者只是:

list1= ['abcd','(1,234)','Level-2 (2):','(31)%', 'others','(3,102.2)%']

print (['-' + item.replace('(','').replace(')','').replace(',','') for item in list1])

输出:

['-abcd', '-1234', '-Level-2 2:', '-31%', '-others', '-3102.2%']