A= ['(100)','(98.2)', '400', '500']
How to replace the list that number with brackets with minus sign? I prefer a simple one line code.
The desired output as below:
A= ['-100','-98.2', '400', '500']
My way is very lengthily
if '(' in A[0]:
A[0] = -float(A[0].translate(None,"(),"))
Option 1
str.strip
+ a list comprehension .
>>> ['-' + y.strip('()') if '(' in y else y for y in A]
['-100', '-98.2', '400', '500']
Option 2
Modifying the first method with a map
+ lambda
.
>>> list(map(lambda y: '-' + y.strip('()') if '(' in y else y, A))
['-100', '-98.2', '400', '500']
Personally, I prefer the list comprehension.
You could also use regex, pretty nice-
import re
res = [re.sub(r"\((.*)\)", r"-\1", x) for x in orig]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.