python - 检查列表的元素是否存在于另一个列表的元素中

标签 python python-2.7

我在处理列表时遇到了一些问题。所以,基本上,我有一个列表:

a=["Britney spears", "red dog", "\xa2xe3"]

我还有另一个列表,看起来像:

b = ["cat","dog","red dog is stupid", "good stuff \xa2xe3", "awesome Britney spears"]

我想做的是检查 a 中的元素是否存在是 b 中某些元素的一部分- 如果是,请将它们从 b 中删除的元素。所以,我想要 b看起来像:

b = ["cat","dog","is stupid","good stuff","awesome"]

什么是最 pythonic(在 2.7.x 中)实现这个的方法?

我假设我可以循环检查每个元素,但我不确定这是否非常有效 - 我有一个大小约为 50k 的列表 ( b)。

最佳答案

我想我会在这里使用正则表达式:

import re

a=["Britney spears", "red dog", "\xa2xe3"]

regex = re.compile('|'.join(re.escape(x) for x in a))

b=["cat","dog","red dog is stupid", "good stuff \xa2xe3", "awesome Britney spears"]

b = [regex.sub("",x) for x in b ]
print (b)  #['cat', 'dog', ' is stupid', 'good stuff ', 'awesome ']

这样,正则表达式引擎可以优化备选列表的测试。

这里有一堆替代方案来展示不同正则表达式的行为方式。

import re

a = ["Britney spears", "red dog", "\xa2xe3"]
b = ["cat","dog",
     "red dog is stupid", 
     "good stuff \xa2xe3", 
     "awesome Britney spears",
     "transferred dogcatcher"]

#This version leaves whitespace and will match between words.
regex = re.compile('|'.join(re.escape(x) for x in a))
c = [regex.sub("",x) for x in b ]
print (c) #['cat', 'dog', ' is stupid', 'good stuff ', 'awesome ', 'transfercatcher']

#This version strips whitespace from either end
# of the returned string
regex = re.compile('|'.join(r'\s*{}\s*'.format(re.escape(x)) for x in a))
c = [regex.sub("",x) for x in b ]
print (c) #['cat', 'dog', 'is stupid', 'good stuff', 'awesome', 'transfercatcher']

#This version will only match at word boundaries,
# but you lose the match with \xa2xe3 since it isn't a word
regex = re.compile('|'.join(r'\s*\b{}\b\s*'.format(re.escape(x)) for x in a))
c = [regex.sub("",x) for x in b ]
print (c) #['cat', 'dog', 'is stupid', 'good stuff \xa2xe3', 'awesome', 'transferred dogcatcher']


#This version finally seems to get it right.  It matches whitespace (or the start
# of the string) and then the "word" and then more whitespace (or the end of the 
# string).  It then replaces that match with nothing -- i.e. it removes the match 
# from the string.
regex = re.compile('|'.join(r'(?:\s+|^)'+re.escape(x)+r'(?:\s+|$)' for x in a))
c = [regex.sub("",x) for x in b ]
print (c) #['cat', 'dog', 'is stupid', 'good stuff', 'awesome', 'transferred dogcatcher']

关于python - 检查列表的元素是否存在于另一个列表的元素中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14646606/

相关文章:

python - 添加 numpy 零数组和屏蔽数组

python - 我想停止 pythoncom 工作

python - 我做的python计算器出错了

Python:导入模块的内存成本

python - SQLite 在使用 flask 和 sqlalchemy 时没有这样的列错误

python - 标准化 pandas groupby 结果

python - 从子类访问 python @property 的值

python - 如何将电压读数限制在写入日志文件的范围内?

python - 删除Python版本3.2.5

python - 在运行时在 Python 中将方法分配给对象