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

84 Views Asked by At

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

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

same question about remove duplicates. 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]
4

There are 4 best solutions below

3
Mehrdad Pedramfar On BEST ANSWER

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 duplicates):

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]

2
Silloky On

This might help you : How to sort two lists (which reference each other) in the exact same way

For removing duplicates, you can use :

ListA = [7,6,3,2,1,4,5]
mylist = list(dict.fromkeys(ListA))

ListB = [a,b,c,d,e,f,g]
mylist = list(dict.fromkeys(ListB))
0
tobias_k On

About the "removing duplicates" bit: You can start as in the other answer, but also pipe the zipped and sorted lists through a dict. In Python 3, a dict will respect the insertion order, but it will keep the last of each key, so you have to reverse the list when sorting, and then reverse back after the dict stage.

>>> listC = [1,1,4,4,5,6,7] 
>>> listD = ["a","b","c","d","e","f","g"]
>>> list(reversed(dict(sorted(zip(listC, listD), reverse=True)).items()))
[(1, 'a'), (4, 'c'), (5, 'e'), (6, 'f'), (7, 'g')]
>>> listC_new, listB_new = zip(*_)
>>> listC_new
(1, 4, 5, 6, 7)
>>> listB_new
('a', 'c', 'e', 'f', 'g')
0
Sharim09 On

For your first part.

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


listB = ['a','b','c','d','e','f','g']
dict_ = {key:value for key,value in zip(listB,listA)}

listA_new = sorted(listA)
listB_new = sorted(listB,key=lambda e:dict_[e])
print(listA_new)
print(listB_new)
OUTPUT
[1, 2, 3, 4, 5, 6, 7]
['e', 'd', 'c', 'f', 'g', 'b', 'a']

For not duplicate items. Try this.

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


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


listC_out = []
listD_out = []
for a,b in zip(listC,listD):
    if a not in listC_out:
        listD_out.append(b)
        listC_out.append(a)

print(listC_out)
print(listD_out)
OUTPUT
[1, 4, 5, 6, 7]
['a', 'c', 'e', 'f', 'g']