Add ranking to Python questions [('a', 14), ('b', 14), ('c', 7), ('d', 6), ('e', 3), ('f', 1)].

Asked 2 years ago, Updated 2 years ago, 85 views

list_a = [('a', 14), ('b', 14), ('c', 7), ('d', 6), ('e', 3), ('f', 1)]

when

[('a', 14, 1), ('b', 14, 1), ('c', 7, 3), ('d', 6, 4), ('e', 3, 5), ('f', 1, 6)]

In this way, I want to rank them in descending order, and I want to give them the same rank for the same value, skip the rank by that number, and rank them next.

What I want here is, how can I add a rank when it's impossible to add elements to a tuple?

dictionary list tuple

2022-09-20 19:38

2 Answers

>>> list_a = [('a', 14), ('b', 14), ('c', 7), ('d', 6), ('e', 3), ('f', 1)]


>>> ranking = 1
>>> list_b = []
>>> for x in list_a:
    list_b.append( list(x)+[ranking] )
    ranking += 1


>>> list_b
[['a', 14, 1], ['b', 14, 2], ['c', 7, 3], ['d', 6, 4], ['e', 3, 5], ['f', 1, 6]]


>>> for i in range(len(list_b)-1):
    b1, b2 = list_b[i], list_b[i+1]
    if b1[1] == b2[1]:
        list_b[i+1][2] = list_b[i][2]


>>> 
>>> list_b
[['a', 14, 1], ['b', 14, 1], ['c', 7, 3], ['d', 6, 4], ['e', 3, 5], ['f', 1, 6]]
>>> list_b = [ tuple(x) for x in list_b ]
>>> list_b
[('a', 14, 1), ('b', 14, 1), ('c', 7, 3), ('d', 6, 4), ('e', 3, 5), ('f', 1, 6)]

There could be a better way.


2022-09-20 19:38

def rankOfList[A, B](L: Seq[(A, B)]): Seq[(A, B, Int)] = {
    @annotation.tailrec
    def _rankOfList[A, B](L: Seq[(A, B)], acc: Seq[(A, B, Int)] = Seq.empty, callCnt:Int = 1): Seq[(A, B, Int)] = L match {
        case Nil => acc
        case x :: xs => _rankOfList(xs, acc :+ (x._1, x._2, if(!acc.isEmpty && acc.last._2 == x._2) acc.last._3 else callCnt), callCnt + 1)
    }
    _rankOfList(L)
}

val list_a = Seq(("a", 14), ("b", 14), ("c", 7), ("d", 6), ("d", 6), ("e", 3), ("f", 1))

rankOfList(list_a)
=> List((a,14,1), (b,14,1), (c,7,3), (d,6,4), (d,6,4), (e,3,6), (f,1,7))


2022-09-20 19:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.