python-3.x - 从另一个列表中删除一组不同值的所有实例?

标签 python-3.x

list1 = [1, 'a', 'c', 3, 5, 3, 3, 'a', 'b']
list2 = ['a', 3, 'b']

是否可以将list2中的值从list1中完全删除并输出:

[1, c, 5]

最佳答案

根据给定的列表,

>>> list1 = [1, 'a', 'c', 3, 5, 3, 3, 'a', 'b']
>>> list2 = ['a', 3, 'b']

使用列表理解

>>> list3 = [item for item in list1 if item not in list2]
>>> list3
[1, 'c', 5]

当我们更改list2时,输出符合预期:

>>> list2 = ['a', 5, 'b']
>>> list3 = [item for item in list1 if item not in list2]
>>> list3
[1, 'c', 3, 3, 3]

关于python-3.x - 从另一个列表中删除一组不同值的所有实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56797911/

相关文章:

python-3.x - 滚动窗口问题 : ValueError: Length of passed values is 3, 索引意味着 2

function - 计算Python中的非空行和这些行的长度总和

python 3 : doctest helper/internal functions?

python-3.x - Python 多线程模块崩溃但没有错误消息

python - OpenCV 裁剪图像并显示裁剪后的原始图像

python - 将列表的列表拆分为每个列表的第一个元素的列表的命令

python-3.x - 如何使用 tkinter 在 Python 中的框架内添加文本和图像

python - 如何在一个方法中递归地不变化由参数传递的数据类型?

python - 从列表中生成多个条件语句

python - 如何将 HTML 代码集成到 Python 脚本中?