Koen Keppel
Koen Keppel

Reputation: 13

Keep only last value in list of lists when first item is duplicate in Python

I'd like to delete an item in a list of lists when the first value of that list is a duplicate of another item in the list.

Let's say I have this list:

[['A', 'Value 1', 'Value 2'],['B', 'Value 3', 'Value 4'],['A', 'Value 5', 'Value 6']]

I'd like to only keep the last list with the value A as first index, like so:

[['B', 'Value 3', 'Value 4'],['A', 'Value 5', 'Value 6']]

Upvotes: 1

Views: 996

Answers (4)

R.A.Munna
R.A.Munna

Reputation: 1709

You can also try this way though it's not an efficient solution.

original = [['A', 'Value 1', 'Value 2'],['B', 'Value 3', 'Value 4'],['A', 'Value 5', 'Value 6'],]
first_element_count = []
for ls in original:
    first_element_count.append(ls[0])
seen, result = set(), []
len_first_element=len(first_element_count)-1
# finding the index of duplicate element and store the first index
while len_first_element>=0:
    item = first_element_count[len_first_element]
    if item not in seen:
        seen.add(item)
    else:
        result.append(len_first_element)

    len_first_element = len_first_element - 1
# removing the list from the list
for i in result:
    del original[i]
print(original)

Upvotes: 0

joshua
joshua

Reputation: 28

l = [['A', 'Value 1', 'Value 2'],['B', 'Value 3', 'Value 4'],['A', 'Value 5', 'Value 6']]
l.pop(0)
print(l)

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Using itertools.groupby() function:

import itertools
l = [['A', 'Value 1', 'Value 2'],['B', 'Value 3', 'Value 4'],['A', 'Value 5', 'Value 6']]
result = [list(g)[-1] for k,g in itertools.groupby(sorted(l), key=lambda x: x[0])]

print(result)

The output:

[['A', 'Value 5', 'Value 6'], ['B', 'Value 3', 'Value 4']]

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599490

You could do this with a dict comprehension; since that builds up a dict by iterating over a list of values, you will always end up with the last duplicate. You can then simply take the values of the dict.

original = [['A', 'Value 1', 'Value 2'],['B', 'Value 3', 'Value 4'],['A', 'Value 5', 'Value 6']]
d = {elem[0]: elem for elem in original}
result = list(d.values())

Upvotes: 6

Related Questions