Python-从另一个列表中删除一组列表 [英] Python - Remove a set of a list from another list

查看:983
本文介绍了Python-从另一个列表中删除一组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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()方法的集合,它返回一个新集合,其中集合中的元素不在作为参数接收的可迭代对象中.请注意,无需为此将array2转换为集合.

The above makes use of the difference() method of sets, which returns a new set with elements in the set that are not in the iterable(s) received as parameter. Notice that there's no need to convert array2 to a set for this to work.

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

Also be aware that by using sets, all duplicate elements will be removed and the original order of the iterables won't necessarily be preserved. If that's an issue, try this alternative solution:

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

这篇关于Python-从另一个列表中删除一组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆