根据第一个条目从数组中删除重复项

时间:2019-11-29 15:23:06

标签: python python-3.x list duplicates slice

我知道很容易从列表中删除重复的项目,例如:

lst = ['a' , 'b' , 'c' , 'c' , 'd' , 'd' ]

使用以下方法:

lst = list(dict.fromkeys(lst))
#output
lst = ['a' , 'b' , 'c' , 'd']

但是,如果列表由2个元素列表组成,则此方法无效:

lst = [['a','1'],['b','2'],['b','1'],['c','3'],['c','2']]

我想删除所有重复第一个元素的条目,而保留第一个元素 每个实例,无论第二个元素如何。因此输出应为:

lst = [['a','1'],['b','2'],['c','3']]

3 个答案:

答案 0 :(得分:4)

您可以使用itertools.groupby

import itertools as it

# use the lambda to group by the first index
# next(g) returns the first instance of the group

[next(g) for k, g in it.groupby(lst, key=lambda x: x[0])]

结果:

[['a', '1'], ['b', '2'], ['c', '3']]

答案 1 :(得分:0)

您可以尝试以下方法:

>>> lst = [['a','1'],['b','2'],['b','1'],['c','3'],['c','2']]
>>> dict(lst)
{'a': '1', 'b': '1', 'c': '2'}

>>> [k for k,_ in dict(lst).items()]
['a', 'b', 'c']

>>> [[k,v] for k,v in dict(lst).items()]
[['a', '1'], ['b', '1'], ['c', '2']]

答案 2 :(得分:0)

lst = [['a', '1'], ['b', '2'], ['b', '1'], ['c', '3'], ['c', '2']]

d = {}
for tupl in lst:
    first = tupl[0]
    if first not in d:
        d[first] = tupl

print(list(d.values()))

输出:

[['a', '1'], ['b', '2'], ['c', '3']]