如何在python中基于正则表达式过滤列表项?

时间:2020-09-23 17:47:45

标签: python list

我有两个列表项,我想根据不匹配的项生成一个列表。这是我正在尝试做的事情:

from __future__ import print_function
import os

mainline_list = ['one', 'two', 'three', 'four']
non_main_list = ['two', 'seven', 'six', 'four', 'four-3.1', 'new_three']
itemized_list = [item for item in non_main_list if item not in mainline_list]
print(itemized_list)

退货是

['seven', 'six', 'four-3.1', 'new_three']

我想要的是:

 ['seven', 'six']

1 个答案:

答案 0 :(得分:1)

不需要正则表达式,可以使用all()内置函数:

mainline_list = ['one', 'two', 'three', 'four']
non_main_list = ['two', 'seven', 'six', 'four', 'four-3.1', 'new_three']

print([item for item in non_main_list if all(i not in item for i in mainline_list)])

打印:

['seven', 'six']