Sort a graph by its weight. python

I have a list of format tuples:

(node1, node2, weight)

What I want to do is sort this tuple so that the nodes with a higher weight are at the top

eg

(A,B,2)
(A,C,5)
(C,A,2)

gotta give me

(A,C,5)
(A,B,2)
(C,A,2)

The first node is sorted alphabetically. Second node according to decreasing weights.

+5
source share
2 answers

This should work fine:

lst.sort(key=lambda x:x[2], reverse=True)

Of course, we can avoid the lambda:

import operator
lst.sort(key=operater.itemgetter(2), reverse=True)

, ( , , ...) , python . , , , node, node . ( ).

( ), :

lst.sort(key=lambda x: (-x[2],x[0])) #relying on tuples

( ), 1 .

, , x[2], (, ). ( ?):

lst.sort(key=lambda x: x[0])
lst.sort(key=lambda x: x[2], reversed=True)
+9

" ". , , , .

A='A'
B='B'
C='C'
lst = [(A, B, 2), (A, C, 5), (C, A, 2)]

def weight_key(tup):
    return tup[0], -tup[2], tup[1]

lst.sort(key=weight_key)
print(lst)  # prints: [('A', 'C', 5), ('A', 'B', 2), ('C', 'A', 2)]

EDIT: . , : ", node . node .

, , , node1; , ; node2. , , .

+5

All Articles