[英]Python: Replace brackets with minus sign in list
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 选项1
str.strip
+ a list comprehension . str.strip
+ 列表理解 。
>>> ['-' + y.strip('()') if '(' in y else y for y in A]
['-100', '-98.2', '400', '500']
Option 2 选项2
Modifying the first method with a map
+ lambda
. 用
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.