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
>>> 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.
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))
611 GDB gets version error when attempting to debug with the Presense SDK (IDE)
914 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
618 Uncaught (inpromise) Error on Electron: An object could not be cloned
572 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
© 2024 OneMinuteCode. All rights reserved.