Alex V
Alex V

Reputation: 23

Search a list in list of lists by first two elements

Let's say we have a sorted list of lists:

l_of_l = [ [1,2,1], [3,4,2], [3,4,5], [3,4,7], [9,10,8], [11,12,9] ]

Sorted by the third value.

Task - to create a new list of the lists with unique first two digits and the smallest third digit.

Expected output:

new_list = [ [1,2,1], [3,4,2], [9,10,8], [11,12,9] ]

We don't have here [3,4,5], [3,4,7], cause we already have an element that starts with 3,4.

Since we already have a sorted list, my idea is to compare x[:-1] and take the first match which will include the smallest third digit by default. But I completely stuck with writing proper code.

The lists can contain chars and integers.

Thank you.

Upvotes: 0

Views: 105

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195418

If your list is already sorted by the third element, you can use temporary dictionary to remove duplicates:

l_of_l = [[1, 2, 1], [3, 4, 2], [3, 4, 5], [3, 4, 7], [9, 10, 8], [11, 12, 9]]


tmp = {}
for a, b, c in l_of_l:
    if (a, b) not in tmp:
        tmp[(a, b)] = c

print([[*k, v] for k, v in tmp.items()])

Prints:

[[1, 2, 1], [3, 4, 2], [9, 10, 8], [11, 12, 9]]

Upvotes: 2

Related Questions