在两个列表中搜索regex match,如果存在则弹出

2024-10-02 22:23:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两张单子

list_one = ['aaa1a', 'bbb21ba', 'ccc4ba', 'qqq55ca']
list_two = ['eee21a', 'sws21ba', 'pop4ba', 'qqq55de']

最后一个数字后面的字母代表一个区域;我已经可以用regex找到这个区域了

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']

我想搜索list\u two以检查它的任何项是否与我的注册表中的任何项匹配,如果匹配,请将其从该列表中删除。所以我会以

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

有没有更好的方法?你知道吗


Tags: in区域列表forlocationfindregone
3条回答

假设您已经获得了reg_list,现在可以使用filter

filter(lambda x: re.findall(regex, x)[0] not in reg_list, list_two)

我不喜欢在看不懂的时候把所有的东西都衬起来。只需考虑最具可读性(当然也是最有效的)解决方案。你知道吗

在迭代列表时不能修改列表。但是你可以创建一个新的

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']

您可以使用列表理解作为一种更简短的替代方法:

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']

相关问题 更多 >