Deemo
Deemo

Reputation: 125

Selecting values in a list to keep based on other repeated values

I have a sorted list of lists (see below). The sub-lists are sorted into the main list by the value at the end, and there are always repeated numbers.

List = [[1,1.5,3],[2,1,3],[4,0,3],[2,3,2],[1,4,2],[1,2,1],[1,1,1],[3,1,1]]

For each sub-list with the same value at the end (ex. the first 3 sub-lists have a 3, the next 2 have a 2, and the last 3 have a 1), I only want to keep the sub-list with the highest second entry.

For example, let's work with the list above. The first 3 sub-lists end in a 3, the max second value in the sub-lists is 1.5, so we keep the sub-list [1,1.5,3] and delete the other two. For the sub-lists ending in 2, 4 is the highest second value so we keep sub-list [1,4,2] and delete the other. Hopefully you get the idea. The ending list is:

newList = [[1,1.5,3],[1,4,2],[1,2,1]]

*In practice the second values in the sub-list are very precise numbers and will never be equal to each other, so there will not be a case were one of them is not the greatest.

Upvotes: 0

Views: 401

Answers (1)

Hugo Alexis
Hugo Alexis

Reputation: 46

Well, I don't know so much about computer science, but I think this works:

List = [[1,1.5,3],[2,1,3],[4,0,3],[2,3,2],[1,4,2],[1,2,1],[1,1,1],[3,1,1]]

new_list = [List[0]]

for item in List[1:]:
    if item[-1] == new_list[-1][-1]:
        if item[1] > new_list[-1][1]:
            new_list[-1] = item
    else:
        new_list.append(item)

print(new_list)

You suppose that always the first list in the main list is which have the highest second entry and add it to the new_list. When you iterate over the items of the main list, if the item in the iteration still have the same 'last value at the end' than the last item added to the new_list, you compare if it have a higher second entry and replace it, otherwise, you add the item to the new_list.

Upvotes: 1

Related Questions