在Python中从列表列表中删除重复项 [英] Removing duplicates from list of lists in Python
问题描述
如果想根据每个嵌套列表的第一个元素评估重复项,谁能提出一个好的解决方案从嵌套列表中删除重复项?
Can anyone suggest a good solution to remove duplicates from nested lists if wanting to evaluate duplicates based on first element of each nested list?
主列表如下:
L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33], ['14', '22', 46]]
如果已经在第一位置[k][0]
处存在另一个具有相同元素的列表,那么我想删除该列表并得到以下结果:
If there is another list with the same element at first position [k][0]
that had already occurred, then I'd like to remove that list and get this result:
L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33]]
您能建议一种实现该目标的算法吗?
Can you suggest an algorithm to achieve this goal?
推荐答案
您是否关心保留订单/删除了哪些重复项?如果没有,那么:
Do you care about preserving order / which duplicate is removed? If not, then:
dict((x[0], x) for x in L).values()
会做到的.如果您想保留订单,并想保留第一个订单,则:
will do it. If you want to preserve order, and want to keep the first one you find then:
def unique_items(L):
found = set()
for item in L:
if item[0] not in found:
yield item
found.add(item[0])
print list(unique_items(L))
这篇关于在Python中从列表列表中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!