python-3.x - 从另一个列表中删除一组不同值的所有实例?
问题描述
list1 = [1, 'a', 'c', 3, 5, 3, 3, 'a', 'b']
list2 = ['a', 3, 'b']
是否可以将 list2 中的值从 list1 中完全删除并输出:
[1, c, 5]
解决方案
With the given lists,
>>> list1 = [1, 'a', 'c', 3, 5, 3, 3, 'a', 'b']
>>> list2 = ['a', 3, 'b']
Use list comprehension
>>> list3 = [item for item in list1 if item not in list2]
>>> list3
[1, 'c', 5]
When we change list2
, the output is as expected:
>>> list2 = ['a', 5, 'b']
>>> list3 = [item for item in list1 if item not in list2]
>>> list3
[1, 'c', 3, 3, 3]
推荐阅读
- cypress - Cypress 通过 aria 角色获取元素
- c# - 尝试使用 protobuf-net 序列化 System.Numerics.Quaternion
- css - 在 React Material UI 表中突出显示 React Material UI TextField “Cell”?
- javascript - 如何将字符串中的数字(无论位数)转换为特定的字符集?
- azure - 如何让 terraform 自动导入所有“已经存在”的资源?
- firebase - 使用 Firebase 使用与 Google 相同的帐户处理 facebook 登录
- r - 包不会通过 RStudio 安装
- php - 使用 AWS PHP SDK 3.x 时,是否可以使用 getCommand 数组将多部分文件并行批量上传到 S3?
- google-analytics - “货币显示为”不会更新 Google Analytics(分析)电子商务报告中的先前数据
- r - 用于创建具有用户指定日期范围和个人的图表的闪亮应用程序