Python - 从另一个列表中删除一组列表

标签 python list set

array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
array2 = [1, 2, 2, 2, 5, 6, 6, 6, 9]

temp = set(array2)

array1.remove(temp)

Traceback (most recent call last):
  File "Sudoku V2.py", line 6, in <module>
    array1.remove(temp)
ValueError: list.remove(x): x not in list

最佳答案

试试这个:

array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
array2 = [1, 2, 2, 2, 5, 6, 6, 6, 9]
set(array1).difference(array2)
=> set([3, 4, 7, 8])

上面使用了 difference()集合的方法,它返回一个新集合,该集合中的元素不在作为参数接收的 iterable(s) 中。请注意,无需将 array2 转换为集合即可使其正常工作。

另请注意,通过使用集合,所有重复元素都将被删除,可迭代对象的原始顺序不一定会保留。如果这是一个问题,请尝试此替代解决方案:

[x for x in array1 if x not in array2]
=> [3, 4, 7, 8]

关于Python - 从另一个列表中删除一组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18819606/

相关文章:

java - 从两个哈希集中删除重复项

python - SQLAlchemy 在 SQL Server 中插入的无效参数类型错误

python - 排序方法 : The truth value of an array with more than one element is ambiguous. 使用 a.any() 或 a.all()

python - Django:测试发送的邮件内容

html - 如何在宽度 : 100% div? 内放置无序列表(导航菜单)

python - 找到使每个字典在多个字典中唯一的键的最小数量

调用操作系统/模块级 python 函数的 Python 单元测试代码

Python:组合列表的列表

python - Python 中 numpy 数组和多维列表的区别?

r - 高效找到集合差异并生成随机样本