下面的列表有一些重复的子列表,元素的顺序不同:
l1 = [
['The', 'quick', 'brown', 'fox'],
['hi', 'there'],
['jumps', 'over', 'the', 'lazy', 'dog'],
['there', 'hi'],
['jumps', 'dog', 'over','lazy', 'the'],
]
如何删除重复项,保留看到的第一个实例,以获得:
l1 = [
['The', 'quick', 'brown', 'fox'],
['hi', 'there'],
['jumps', 'over', 'the', 'lazy', 'dog'],
]
我尝试过:
[list(i) for i in set(map(tuple, l1))]
不过,我不知道这是否是处理大型列表的最快方法,而且我的尝试没有达到预期效果。知道如何有效地移除它们吗?
最佳答案
这个有点棘手。你想从卡住的计数器中键入一个命令,但计数器在 Python 中不可散列。对于渐近复杂性的小幅退化,您可以使用排序的元组代替卡住计数器:
seen = set()
result = []
for x in l1:
key = tuple(sorted(x))
if key not in seen:
result.append(x)
seen.add(key)
同样的想法在一行中看起来像这样:
[*{tuple(sorted(k)): k for k in reversed(l1)}.values()][::-1]
关于python - 从列表列表中有效地删除与顺序无关的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57466243/