python从另一个列表中删除列表

标签 python list set frozenset

有两个列表,比如

[[A, A], [B, B], [C, C], [D, D]]

[[A, A], [B, B]]

如何从结果为 [[C, C], [D, D]] 的列表 1 中删除列表 2 并使其不带循环,因为两个列表都非常大且循环运行缓慢?

谢谢 列举例子

>>>a = [[9, 9], [8, 8], [7, 7], [6, 6], [4, 4], [5, 5], [12, 12], [15, 15], [2, 2], [3, 3]] 

>>>b = [[4, 4], [5, 5]]

form要求写我已经试过的,OK,在下面 尝试一:(不行,而且里面有一个循环)

def rightdotsremowe (ax, bx): 
    for o in set(bx):
        try:
            ax.remove(o) 
        except ValueError:
            pass
    return ax

尝试二(看起来更好但也行不通)

newlist00 = [x for x in a if (x not in e)]

最佳答案

如果顺序对您来说不是很重要,sets 会明显更快。所以你可以试试这个,它会比列表更快。

a=[['A', 'A'], ['B', 'B'], ['C', 'C'], ['D', 'D']]

a={tuple(i) for i in a}

并尝试使用difference方法:

return new set with elements in a but not in b

平均情况 O(len(a))

a=[['A', 'A'], ['B', 'B'], ['C', 'C'], ['D', 'D']]
b=[['A', 'A'], ['B', 'B']]

a={tuple(i) for i in a}
b={tuple(i) for i in b}

print a.difference(b)

那是因为 set 使用哈希函数映射到一个桶。由于 Python 实现会自动调整该哈希表的大小,因此速度可以保持不变 O(1)

Set 在确定一个对象是否在 set 中要快得多,但在迭代其内容时比 lists 慢。

希望这对您有所帮助。

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

相关文章:

python - 我如何从 django 中的 forms.ModelChoiceField 获取值?

list - 如何在Scala中减去列表中的两个连续元素?

python - Python 有一个不可变的列表吗?

java - 在spring ioc中定义一个bean之外的集合

c++ - 从 unordered_multiset 中只删除一项

python - lxml 返回 DTD 属性的空列表

python - 为什么在 python 脚本中使用记录器时会在记录器中写入 null ?

python - pip force reinstall in requirements.txt

Java,向列表添加一个值<pair>

python - 用于字符串查找的集合与正则表达式,哪个更具可扩展性?