我有以下列表
x = ['Accara building model (ABM)','tri-com model (tcm)']
使用 re 我可以忽略括号中的单词。就像下面这样
import re
x = ['Accara building model (ABM)','tri-com model (tcm)']
for i in x:
ko= list(re.sub("[\(\[].*?[\)\]]", "", i))
print (ko)
但我得到以下格式的输出
['A', 'c', 'c', 'a', 'r', 'a', ' ', 'b', 'u', 'i', 'l', 'd', 'i', 'n', 'g', ' ', 'm', 'o', 'd', 'e', 'l', ' ']
['t', 'r', 'i', '-', 'c', 'o', 'm', ' ', 'm', 'o', 'd', 'e', 'l', ' ']
我理想中想要的是像下面这样用尽可能少的代码行。 (我知道我的代码目前效率很低)
需要理想的输出
['Accara building model', 'tri-com model']
最佳答案
您不应该使用list()
,但您应该在循环之前创建空列表并将结果附加到此列表
import re
x = ['Accara building model (ABM)','tri-com model (tcm)']
results = []
for i in x:
ko = re.sub("[\(\[].*?[\)\]]", "", i)
resutls.append(ko.strip())
print(results)
结果
['Accara building model', 'tri-com model']
您甚至可以使用列表理解
import re
x = ['Accara building model (ABM)','tri-com model (tcm)']
results = [re.sub("[\(\[].*?[\)\]]", "", i).strip() for i in x]
print(results)
顺便说一句:我使用strip()
删除末尾的空格。但是您可以使用以空格 "[\(\[].*?[\)\]]"开头的正则表达式删除此空格。
.
编辑:正如 Mark Meyer 在评论中建议的那样,您还可以编译正则表达式 - 因此不必在每个循环中都执行此操作。
x = ['Accara building model (ABM)','tri-com model (tcm)']
pattern = re.compile(" [\(\[].*?[\)\]]")
results = [re.sub(pattern, "", i) for i in x]
print(results)
顺便说一句:如果您确定元素始终具有相同的结构,那么您可以在不使用正则表达式的情况下删除它,但使用 split(' (')
x = ['Accara building model (ABM)','tri-com model (tcm)', 'name without parentheses']
results = [i.split(' (',1)[0] for i in x]
print(results)
关于python - 忽略列表中包含括号的单词的最有效(Pythonic)方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59128121/