Home > Mobile >  Sort array output formatting to another array
Sort array output formatting to another array

Time:02-10

array1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
array2 = [ "c", "a","b"]
Z = [x for _,x in sorted(zip(array1,array2))]
print(Z)

I'm trying to write a code to sort the array in the format of another array.

For this code I want to get the value of Z to be ["a","b","c"] as is mentioned first in array1.

The above code is giving output as ['c', 'a', 'b'].

I want the output to ['a', 'b', 'c'] as the array1 is mentioned as 'a' is given as array1[0] so I want the Z[0] to be 'a'.

CodePudding user response:

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

CodePudding user response:

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

  • Related