Home > Software engineering >  Sort or remove elements from corresponding list in same way as in reference list
Sort or remove elements from corresponding list in same way as in reference list

Time:06-26

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 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]

CodePudding user response:

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]

CodePudding user response:

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']

CodePudding user response:

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

CodePudding user response:

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')
  • Related