Home > Enterprise >  Sort array output python
Sort array output python

Time:02-14

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

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

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