我想从列表中的子列表的所有元素中删除特殊字符。我该怎么做呢?
list = [['abch', 'def',1,11],['cdjje', 'fef',2,22],['oefg', 'pqkjbr',3,33]]
'abc', 'def'是一个字符串,','应该用空格替换。预期输出为:
list = [['abch def',1,11],['cdjje fef',2,22],['oefg pqkjbr',3,33]]
我正在尝试下面的代码,但它似乎不工作:
value_list=[]
for idx, item in enumerate(list):
value_list[idx] = re.sub(r"', '"," ", str(item[0:-2]))
print(value_list)
我希望这是你正在寻找的。$在正则表达式中有特殊的含义(应该匹配字符串的末尾),因此使用反斜杠$。
output_list = l_list.copy()
for l_idx, l_item in enumerate(l_list):
for i_idx, i_item in enumerate(l_item):
if isinstance(i_item, str):
output_list[l_idx][i_idx] = re.sub(r"$","", i_item)
print(output_list)
可以使用
lst = [['abc', 'def',1,11],['cde', 'fef',2,22],['efg', 'pqr',3,33]]
result = []
for l in lst:
res = []
for i, s in enumerate(l):
if isinstance(s, str):
if len(res) > 0 and isinstance(res[i-1], str):
res[i-1] += f" {s}"
else:
res.append(s)
else:
res.append(s)
result.append(res)
print(result)
# => [['abc def', 1, 11], ['cde fef', 2, 22], ['efg pqr', 3, 33]]
参见Python演示。注意:不要将变量命名为内置变量,list
是Python内置的,您可以使用其他名称作为列表,如lst
,l
等。
This:
import re
thelist = [['abc$', 1, 11], ['cde$', 2, 22],['efg$', 3, 33]]
regex = re.compile(r'$')
newlist = [[regex.sub('', x) if isinstance(x, str) else x for x in l] for l in thelist]
print(newlist)
打印:
[['abc', 1, 11], ['cde', 2, 22], ['efg', 3, 33]]
对于新问题:
:
thelists = [['abch', 'def', 1, 11], ['cdjje', 'fef', 2, 22], ['oefg', 'pqkjbr', 3, 33]]
newlist = []
for thelist in thelists:
tmplist = []
for item in thelist:
if len(tmplist) and isinstance(item, str) and isinstance(tmplist[-1], str):
tmplist[-1] += item
else:
tmplist.append(item)
newlist.append(tmplist)
print(newlist)
打印:
[['abchdef', 1, 11], ['cdjjefef', 2, 22], ['oefgpqkjbr', 3, 33]]