Search code examples
pythonsortingranking

How to rank elements within a 2D array


I have an array of data representing web page traffic that is structured like this, where element 0 of each item is the page name, element 1 is pageviews and element 2 is number of users

[['page 1 name','3678','400']['page 2 name','4000','123']['page 3 name','3802','750']]

How do I go about ranking these items by pageviews and number of users and appending the ranks to the end of the array elements, to end up with

[['page 1 name','3678','400','3','2']['page 2 name','4000','123','1','3']['page 3 name','3802','750','2','1']]

Apologies for not including any code, but I've searched everywhere and can't find any clue about where to start with this.


Solution

  • The simplest logic, sort and append the index to the end

    lst = [['page 1 name','3678','400'], ['page 2 name','4000','123'], ['page 3 name','3802','750']]
    
    views_lst = sorted(lst, key=lambda x: int(x[1]), reverse=True)
    numbers_lst = sorted(lst, key=lambda x: int(x[2]), reverse=True)
    for sorted_item in [views_lst, numbers_lst]:
        lst = [item + [str(sorted_item.index(item[:3]) + 1)] for item in lst]
    print(lst)
    

    OUTPUT:

    [['page 1 name', '3678', '400', '3', '2'], ['page 2 name', '4000', '123', '1', '3'], ['page 3 name', '3802', '750', '2', '1']]