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

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

最佳答案

正则表达式不是必需的,您可以使用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']

关于python - 如何在python中基于正则表达式过滤列表项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64033574/

相关文章:

list - 在 Groovy 的多重赋值中获取列表的尾部

python - 按索引创建嵌套列表的最小值列表

python - 从 ALPHANUMERIC 中查找缺失的数字 - Python

python - 将行转置为列,同时根据组展平数据框

python - 如何通过 URL 过滤 Flask-peewee 中的查询?

python - 在 openpyxl 中保留原始单元格格式

java - 如果迭代已经同步,是否有必要使用synchronizedList而不是List?

python - 按字母顺序对元组列表进行排序(区分大小写)

python - 使用 keras ImageDataGenerator 时如何在测试阶段对图像应用标准化?

python - 在 Python 2.7 上使用 Py2app 编译应用程序时出现错误(引发 ImportError ("No module named "+ qname))