Skip to content Skip to sidebar Skip to footer

Sorting An Array Based On Another Array

I have two lists A=[5,2,3,4,1] B=[3,1,5] I want to sort B using A such that the output reflects: [5,3,1] How can I implement this?

Solution 1:

You could use... but all depends on what you're after - there are other ways...

>>>a = [5, 2, 3, 4, 1]>>>b=  [3, 1, 5]>>>sorted(b, key=a.index)
[5, 3, 1]

Or as @Manan has pointed out - you can in-place sort using a.sort(...)

Solution 2:

For an in place sort this should do it:

B.sort(key=A.index)

Otherwise you could do this (as per Jon Clements...):

BSorted = B.sorted(key=A.index)

How this works:

The key argument is a function (it's pretty common to use lambdas here...) The list is sorted according to the output of the function. The example below illustrates:

A = [{'a':100,'b':10},{'a':56,'b':100},{'a':90,'b':90}]
A.sort(key=lambda x:x['a']) 
print(A)
A.sort(key=lambda x:x['b']) 
print(A)

This outputs:

[{'a':56,'b':100},{'a':90,'b':90},{'a':100,'b':10}][{'a':100,'b':10},{'a':90,'b':90},{'a':56,'b':100}]

Solution 3:

If my understanding of your question is right, you want to do the following:

A = [5,2,3,4,1]
B = [3,1,5]
C = []
for i in range(len(A)):
    if A[i] in B:
        C += [A[i]]

print C # [5, 3, 1]

Hope this helps.

Post a Comment for "Sorting An Array Based On Another Array"