python - 忽略列表中包含括号的单词的最有效(Pythonic)方法是什么?

标签 python regex python-3.x string list

我有以下列表

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/

相关文章:

当同一模块存在于 2 个位置时,python __import__() 从 2 个不同的目录导入

Python特定的PATH环境变量?

python - 我无法使用 h5py 读回数据。 "unable to create group"

python - 如何得到正确的十进制结果

macos - 在 Mac OS Lion 上为 Python3 构建 numpy/scipy

python - SyntaxError : multiple statements found in python. 有人有这方面的经验吗?

javascript - 如何在 js 中验证字符串仅包含来自多个 unicode 范围的字符

php - 为什么在这种情况下使用 RewriteCond 和 RewriteRule 重定向会失败?

javascript - 正则表达式或 jQuery 以迭代计数进行查找/替换

class - python 3 中的 types.ClassType 发生了什么?