[Python] `sorted` isn't actually sorting the whole list. Wierd sorted behavior on list of...

Discussão em 'Python' iniciado por Stack, Outubro 23, 2024.

  1. Stack

    Stack Membro Participativo

    I have a dict which values are tuple of 3 elements.

    I would like to sort elements of the dict with respect to the 3-rd element of the tuple therefore:

    sorted(d.values(), key=lambda t: t[2])


    However it does not seems to give the right order because the first element isn't the minimum:

    In [80]: d[k][2] # there is a key `k` such that its 3rd value is 2.6
    Out[80]: 2.6581503328936367

    In [81]: sorted(list(d.values()), key=lambda t: t[2])[0][2]
    Out[81]: 3.4480075912282135


    Here getting element 0 of the sorted list of value (thus, the minimum) gives 3.44 even though we just checked that there is an element k that has 2.65 < 3.44 as its 3rd tuple value.

    Even stranger explicitely adding 1 < 3.44 does not lower the minimum:

    In [79]: sorted(list(d.values())+[(0,0,1)], key=lambda t: t[-2])[0][2]
    Out[79]: 3.9262885493340858


    Unless I "prepend" it, why is the order important here:

    In [84]: sorted([(0,0,1)] + list(d.values()), key=lambda t: t[-2])[0][2]
    Out[84]: 1


    I consider myself senior python dev and really does not understand whats going on.

    Any idea?

    Continue reading...

Compartilhe esta Página