I have two lists which have been created by .csv files. The first consists of a branch id number and a list of corresponding flows. The second is the order in which I wish to have the branche ids and their corrsponding flows sorted. They are as follows:
branch_flows = [['1234-2321-1', [55, 76, 3, 55, 6]],
['1546-2645-1', [4, 6, 56, 3, 4]],
// ...
['4123-1234-1', [6, 12, -4, 7, 9]]
]
and
ordered_branches = ['1234-2321-1',
'1234-4123-1',
// ...
'1546-2645-1']
I am wondering how to sort branch_flows the same way ordered_branches is ordered, but for the flows to stay related to the same ids after sorting? The main difficulty being that some of the branch ids in branch_flows first two parts are reversed, but I need them to be sorted as if they were not.
e.g. looking to the lists above, desired output would be having branch_flows sorted in a way that the final list in branch_flows was placed second in the sorted list (as 1234-4123-1 in ordered_branches can equal both 1234-4123-1 AND 4123-1234-1 in branch_list, as the order in branch_flows can sometimes be the reverse of that in ordered_branches).
I originally tried to use dictionarys as look up tables but ran into trouble with the reading reverse order part. Help much appreciated!
You need to construct an appropriate
keyfunction to the Pythonsortfunction.Ignoring the reversed-order issue, it’s quite easy:
Considering the reversed-order issue, we can use:
Now you can sort
branch_flowsassorted(branch_flows, key=key).You can speed this up by turning
ordered_branchesinto a dictionary:and instead of
ordered_branches.index(id)useorder_dict[id](also changeValueErrortoKeyError).As a time-space tradeoff you could construct the reversed-order ids in the dict:
Now your key function just looks like: