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

问题描述 投票:0回答:3

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

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']]
python python-3.x list duplicates slice
3个回答
3
投票

您可以使用itertools.groupby

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])]

0
投票

您可以尝试以下方法:

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

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']]

输出:

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()))
© www.soinside.com 2019 - 2024. All rights reserved.