且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Python的列表列表中删除重复的列表

更新时间:2023-01-21 23:36:21

(ab)使用列表组件的副作用版本:

(ab)using side-effects version of a list comp:

seen = set()

[x for x in g if frozenset(x) not in seen and not seen.add(frozenset(x))]
Out[4]: [[1, 2, 3], [9, 0, 1], [4, 3, 2]]

对于那些不喜欢以这种方式使用副作用的人(与我不同):

For those (unlike myself) who don't like using side-effects in this manner:

res = []
seen = set()

for x in g:
    x_set = frozenset(x)
    if x_set not in seen:
        res.append(x)
        seen.add(x_set)

frozenset添加到集合中的原因是,您只能将可哈希对象添加到set,而普通set不可哈希.

The reason that you add frozensets to the set is that you can only add hashable objects to a set, and vanilla sets are not hashable.