基于前两个元素从嵌套列表中删除重复项 [英] Removing Duplicates from Nested List Based on First 2 Elements
问题描述
仅在前两个元素相同的情况下,我才尝试从嵌套列表中删除重复项,而忽略了第三个...
I'm trying to remove duplicates from a nested list only if the first 2 elements are the same, ignoring the third...
列表:
L = [['el1','el2','value1'], ['el3','el4','value2'], ['el1','el2','value2'], ['el1','el5','value3']]
会返回:
L = [['el3','el4','value2'], ['el1','el2','value2'], ['el1','el5','value3']]
我找到了一种简单的方法来进行类似的操作在这里:
I found a simple way to do similar here:
dict((x[0], x) for x in L).values()
但这仅适用于第一个元素,不适用于第一个2元素,但这正是我想要的.
but this only works for the first element and not the first 2, but that is exactly what i want otherwise.
推荐答案
如果顺序无关紧要,则可以使用相同的方法,但是将第一和第二个元素的元组用作键:
If the order doesn't matter, you can use that same method but using a tuple of the first and second elements as the key:
dict(((x[0], x[1]), x) for x in L).values()
或者在Python 2.7和更高版本上:
Or on Python 2.7 and higher:
{(x[0], x[1]): x for x in L}.values()
您可以使用tuple(x[:2])
代替(x[0], x[1])
,只要您认为可读性更高即可.
Instead of (x[0], x[1])
you can use tuple(x[:2])
, use whichever you find more readable.
这篇关于基于前两个元素从嵌套列表中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!