如何从列表中的元素中删除括号(Python)

时间:2015-09-29 18:14:21

标签: python list parentheses

我试图从列表中的数字中删除一些括号。例如,我有以下列表

[' 103.92246(11)\n'],
[' 104.92394(11)\n'],
[' 105.92797(21)#\n'],
[' 106.93031(43)#\n'],
[' 107.93484(32)#\n'],
[' 108.93763(54)#\n'],
[' 109.94244(54)#\n'],
[' 110.94565(54)#\n'],
[' 111.95083(75)#\n'],
[' 112.95470(86)#\n'],
[' 82.94874(54)#\n'],
[' 83.94009(43)#\n'],
[' 84.93655(30)#\n'],
[' 85.93070(47)\n'],
[' 86.92733(24)\n'],
...]

例如,对于我的列表中的第一个元素,我有103.92246(11),我想从中剥离它以给出103.92246。有些元素也有#我想要删除,基本上我想要的只是浮点数。我该怎么做呢? 我已尝试过以下代码,但这似乎并不适合我。

tolist = []
for num in mylist:
  a = re.sub('()', '', num)
tolist.append(a)

4 个答案:

答案 0 :(得分:3)

您可以使用str.translate,传递您要删除的字符:

l =[[' 103.92246(11)\n'],
[' 104.92394(11)\n'],
[' 105.92797(21)#\n'],
[' 106.93031(43)#\n'],
[' 107.93484(32)#\n'],
[' 108.93763(54)#\n'],
[' 109.94244(54)#\n'],
[' 110.94565(54)#\n'],
[' 111.95083(75)#\n'],
[' 112.95470(86)#\n'],
[' 82.94874(54)#\n'],
[' 83.94009(43)#\n'],
[' 84.93655(30)#\n'],
[' 85.93070(47)\n'],
[' 86.92733(24)\n']]

for sub in l:
    sub[:] = [s.translate(None, "()#") for s in sub]

输出:

[[' 103.9224611\n'], [' 104.9239411\n'], [' 105.9279721\n'], 
[' 106.9303143\n'], [' 107.9348432\n'], [' 108.9376354\n'],
 [' 109.9424454\n'], [' 110.9456554\n'], [' 111.9508375\n'],
 [' 112.9547086\n'], [' 82.9487454\n'], [' 83.9400943\n'], 
[' 84.9365530\n'], [' 85.9307047\n'], [' 86.9273324\n']]

如果你想让它们投射到花车:

 sub[:] = map(float,(s.translate(None, "()#") for s in sub))

会给你:

[[103.9224611], [104.9239411], [105.9279721], [106.9303143], 
[107.9348432], [108.9376354], [109.9424454], [110.9456554], 
[111.9508375], [112.9547086], [82.9487454], [83.9400943], [84.936553], 
 [85.9307047], [86.9273324]]

如果你想删除parens中的nums,请拆分第一个(

for sub in l:
    sub[:] = map(float,(s.rsplit("(",1)[0] for s in sub))

print(l)

输出:

[[103.92246], [104.92394], [105.92797], [106.93031], [107.93484], 
[108.93763], [109.94244], [110.94565], [111.95083], [112.9547], 
[82.94874], [83.94009], [84.93655], [85.9307], [86.92733]]

或使用str.rfind

for sub in l:
    sub[:] = map(float,(s[:s.rfind("(")] for s in sub))

输出如上。

答案 1 :(得分:1)

您的正则表达式有一点变化:

tolist = []
for num in mylist:   
  a = re.sub(r'\(.*\)', '',num)
  tolist.append(a)

答案 2 :(得分:0)

你可以这样做:

result = []
for num in mylist:
    a = num[0].index('(') #find the position of (
    result.append(num[0][:a])

oneliner版本

[x[0][:x[0].index('(')] for x in mylist]

答案 3 :(得分:-1)

import re    

my_list = [[' 103.92246(11)\n'],
[' 104.92394(11)\n'],
[' 105.92797(21)#\n'],
[' 106.93031(43)#\n'],
[' 107.93484(32)#\n'],
[' 108.93763(54)#\n'],
[' 109.94244(54)#\n'],
[' 110.94565(54)#\n'],
[' 111.95083(75)#\n'],
[' 112.95470(86)#\n'],
[' 82.94874(54)#\n'],
[' 83.94009(43)#\n'],
[' 84.93655(30)#\n'],
[' 85.93070(47)\n']]    

result = [re.sub(r'([0-9\.])\(.*?\n', r'\1', x[0]) for x in my_list]