jakedag
jakedag

Reputation: 31

tuple sorting of graphs by certain list(edgeweight)

I have developed a tuple that looks as follows:

(['Austin', 'Austin', 'Houston', 'Dallas', 'Dallas', 'San Antonio'], ['San Antonio', 'El Paso', 'Austin', 'Austin', 'Houston', 'El Paso'], [1, 8, 3, 7, 3, 8])

Each city name is a label and the numbers in the third list represent the edge weights of the vertices. How would I be able to sort this tuple by the third set that would allow the vertices to be sorted according to the weight. For example,

Austin--San Antonio 1
Houston--Austin 3
Dallas--Houston 3
Dallas--Austin 7
Austin--El Paso 8
San Antonio--El Paso 8

Upvotes: 1

Views: 47

Answers (1)

vaultah
vaultah

Reputation: 46523

Using zip and sorted functions:

In [54]: srtd = sorted(zip(*t), key=lambda x: x[-1])

In [55]: srtd
Out[55]: 
[('Austin', 'San Antonio', 1),
 ('Houston', 'Austin', 3),
 ('Dallas', 'Houston', 3),
 ('Dallas', 'Austin', 7),
 ('Austin', 'El Paso', 8),
 ('San Antonio', 'El Paso', 8)]

where t is your tuple. If you need to convert the result back to tuple:

In [56]: tuple(zip(*srtd))
Out[56]: 
(('Austin', 'Houston', 'Dallas', 'Dallas', 'Austin', 'San Antonio'),
 ('San Antonio', 'Austin', 'Houston', 'Austin', 'El Paso', 'El Paso'),
 (1, 3, 3, 7, 8, 8))

Upvotes: 6

Related Questions