如何在python中为字符串添加括号

问题描述

我有一个字符串,我想转换为带括号的列表或字符串。我该怎么做?

字符串为 st = ((22027.0 22943.0,22026.0 22939.0,22025.0 22936.0,22025.0 22932.0,22027.0 22929.0,22030.0 22926.0,22031.0 22922.0,22033.0 22919.0,22033.0 22907.0,22030.0 22908.0,22029.0 22911.0)) 所需的输出应如下所示:

([(22027.0,22943.0),(22026.0,22939.0),(22025.0,22936.0),22932.0),(22027.0,22929.0),(22030.0,22926.0),(22031.0,22922.0),(22033.0,22919.0),22907.0),22908.0),(22029.0,22911.0)])

到目前为止我尝试了什么?

s = str('((22027.0 22943.0,22029.0 22911.0))')
op = s.replace(',','),(')

这不会给出所需的输出。我如何获得以下输出?

([(22027.0,22911.0)])

解决方法

去掉括号后会更容易。

从那里,您可以拆分逗号并从成对的字符串中形成元组(将它们转换为浮点数之后)

一位评论者有一个很好的单行,但这是一个 for 循环:

st =  "((22027.0 22943.0,22026.0 22939.0,22025.0 22936.0,22025.0 22932.0,22027.0 22929.0,22030.0 22926.0,22031.0 22922.0,22033.0 22919.0,22033.0 22907.0,22030.0 22908.0,22029.0 22911.0))"
st = [x.strip() for x in st[2:-2].split(",")]
res = []
for x in st:
    res.append(tuple(float(y) for y in x.split()))
print(res)
,

如果你想要一个字符串列表的结果,你可以组合replacelambdamap

list(map(lambda x: f'({x.strip().replace(" ",",")})',st[2:-2].split(',')))

#output: ['(22027.0,22943.0)','(22026.0,22939.0)','(22025.0,22936.0)',22932.0)','(22027.0,22929.0)','(22030.0,22926.0)','(22031.0,22922.0)','(22033.0,22919.0)',22907.0)',22908.0)','(22029.0,22911.0)']

如果您希望结果为具有浮点值的元组列表,您可以在上述方法之上使用 eval

list(map(lambda x: eval(f'({x.strip().replace(" ",")})'),')))

#output: [(22027.0,22943.0),(22026.0,22939.0),(22025.0,22936.0),22932.0),(22027.0,22929.0),(22030.0,22926.0),(22031.0,22922.0),(22033.0,22919.0),22907.0),22908.0),(22029.0,22911.0)]
,
  • 去掉前后括号。
  • , 处拆分结果字符串。
  • 现在将每个 string 转换为 float 并创建一个 tuple
  • 将那些 tuples 附加到列表中。
st =  "((22027.0 22943.0,22029.0 22911.0))"
st = st[2:-2]
s = st.split(',')

res = []

for i in s:
    res.append(tuple(map(float,i.split())))

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...