0
array1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]

I'm trying to write a code to sort the array

3
  • 1
    replace _,x with x,_ Commented Feb 9, 2022 at 19:46
  • 1
    what's I'm trying to write a code to sort the array in the format of another array meaning? Commented Feb 9, 2022 at 19:50
  • X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] Y = [ "i", "a","e"] Z = [x for x,_ in sorted(zip(X,Y))] print(Z) While printing this i wanted the output of Z to be ["a","e","i"] but i'm getting ['a', 'b', 'c'] Commented Feb 9, 2022 at 19:55

2 Answers 2

1

Using list comprehension, you can do the following:

array1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
array2 = [ "c", "a","b"]

Z = [b for b in array1 if any(b in a for a in array2)]
print(Z)

Output:

['a', 'b', 'c']
Sign up to request clarification or add additional context in comments.

Comments

0

Not clear what "sort the array in the format of another array" meams? If you mean sort a subset of the aray so that the order in the subset is the same as the order in the array, you can use something like

sorted(array2,key = lambda k:array1.index(k))

which will sort array2 so that any two elements of array2 are in the same order as in array 1. Note "subset" is needed. This will fail if there is an element of array2 that is not in array1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.