+ 2

How to sort dependent lists

I have 3 lists A B & C. all are of the same length. list A needs to be sorted but list B and C also needs to change its orders to reflect the sorting to maintain the value relationships between the three lists. I am unsure how to achieve this with python.

15th Feb 2018, 1:04 AM
Kevin Oudai
Kevin Oudai - avatar
2 Respostas
+ 3
# Convert your three lists in a unique list of dicts/objects, then sort this list by key: list1 = [ 7, 2, 5 ] list2 = [ 'b', 'a', 'c' ] list3 = [ 42, 64, 32 ] ulist = [ ] for i in range(len(list1)): ulist.append({ 'list1' : list1[i], 'list2' : list2[i], 'list3' : list3[i] }) ulist.sort(key=lambda v: v['list2']) # if necessary, you can convert back the unique list to three separated ones: list1 = [ ] list2 = [ ] list3 = [ ] for index in range(len(ulist)): list1.append(ulist[index]['list1']) list2.append(ulist[index]['list2']) list3.append(ulist[index]['list3']) # you could use list comprehension also, but for long list this will be less efficient, as you need iterate 3 times over the unique list instead of only once: list1 = [ value['list1'] for value in ulist ] list2 = [ value['list2'] for value in ulist ] list3 = [ value['list3'] for value in ulist ]
15th Feb 2018, 3:57 AM
visph
visph - avatar
+ 2
i did not use a list of dictionaries since the items in the main sorting list is non unique. I used a list of lists and i was able to achieve sorting as I desired it thank you for pointing me in the right direction.
16th Feb 2018, 9:09 PM
Kevin Oudai
Kevin Oudai - avatar