Python 在两个列表中搜索正则表达式匹配项,如果存在,则搜索pop
我有两张单子Python 在两个列表中搜索正则表达式匹配项,如果存在,则搜索pop,python,Python,我有两张单子 list_one = ['aaa1a', 'bbb21ba', 'ccc4ba', 'qqq55ca'] list_two = ['eee21a', 'sws21ba', 'pop4ba', 'qqq55de'] 最后一个数字后面的字母代表一个区域;我已经可以用正则表达式找到这个了 regex = re.compile(r"[^[0-9]+$") reg_list = [] for i in list_one: reg_list.append(regex.findall(
list_one = ['aaa1a', 'bbb21ba', 'ccc4ba', 'qqq55ca']
list_two = ['eee21a', 'sws21ba', 'pop4ba', 'qqq55de']
最后一个数字后面的字母代表一个区域;我已经可以用正则表达式找到这个了
regex = re.compile(r"[^[0-9]+$")
reg_list = []
for i in list_one:
reg_list.append(regex.findall(i))
这会给
reg_list = [u'a', u'ba', u'ba', u'ca']
我想搜索列表2以检查它的任何项目是否与我的注册列表中的任何项目匹配,如果匹配,则将其从该列表中删除。所以我会以
list_two = ['qqq55de']
因为“de”是唯一不在列表中的位置。我现在的代码是
for i in list_one:
for j in list_two:
find_location = regex.findall(j)
if a == find_location:
list_two.pop(j)
但是我得到了错误
TypeError: expected string or buffer
是否有更好的方法执行此操作?您可以使用列表理解作为一种更短、更简洁的替代方法:
import re
list_one = ['aaa1a', 'bbb21ba', 'ccc4ba', 'qqq55ca']
list_two = ['eee21a', 'sws21ba', 'pop4ba', 'qqq55de']
new_list_two = [i for i in list_two if any(re.sub('[a-zA-Z]+$', '', i) == re.sub('[a-zA-Z]+$', '', b) for b in list_one)]
输出:
['qqq55de']
假设您已经获得了
reg\u列表
,现在可以使用过滤器
:
filter(lambda x: re.findall(regex, x)[0] not in reg_list, list_two)
我不喜欢在看不懂的时候把每件事都写下来。只需考虑最可读的(当然是最有效的)解决方案。< /P> < P>在迭代时不能修改列表。但是你可以创建一个新的
import re
list_one = ['aaa1a', 'bbb21ba', 'ccc4ba', 'qqq55ca']
list_two = ['eee21a', 'sws21ba', 'pop4ba', 'qqq55de']
regex = re.compile(r"[^0-9]+$")
reg_list = []
for i in list_one:
reg_list.append(regex.findall(i)[0])
list_two = [j for j in list_two if regex.findall(j)[0] not in reg_list]
print(list_two)
结果:
['qqq55de']
你在哪一行得到这个错误?