Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort or remove elements from corresponding list in same way as in reference list

I have two lists in python of same length:

listA = [7,6,3,2,1,4,5]

listB = [a,b,c,d,e,f,g]

is their some way (probably easy function) to sort listA and change the values of listB in the same way. Means

listA_new = [1,2,3,4,5,6,7]

and

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

listB_new = [e,d,c,f,g,b,a]

same question about remove dublicates. E.g. if I have some list

listC = [1,1,4,4,5,6,7] 

and

listD = [a,b,c,d,e,f,g]

the result should be:

listC_new = [1,4,5,6,7]

and

listD_New = [a,c,e,f,g]

>Solution :

Try this:

[i for j, i in sorted(zip(listA, listB))]

output:

listA = [7, 6, 3, 2, 1, 4, 5]
listB = ["a", "b", "c", "d", "e", "f", "g"]

In [5]: [i for j, i in sorted(zip(listA, listB))]
Out[5]: ['e', 'd', 'c', 'f', 'g', 'b', 'a']

for supporting C and D (removing dupplicates):

sorted(list({j: i for j, i in reversed(sorted(zip(listC, listD)))}.values()))

.values() returns ListD:['a', 'c', 'e', 'f', 'g'] and .keys() returns ListC:[1, 4, 5, 6, 7]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading