-1

Say I have two lists: test (1st one which will be the sorted one), and sort (which is the sorting index of the other list):

test
[16, 44, 12, 43, 17, 22, 6, 20, 41, 21]

sort
[20, 40, 43, 41, 29, 2, 14, 27, 44, 16 42, 21, 3, 22, 9, 32, 17, 23, 1, 
 31, 24, 19, 10, 33, 25, 26, 5, 30, 12, 28, 18, 8, 6, 15, 7, 13, 11, 4] 

How can I sort test based on the matrix position? This would be my desired solution:

[20, 43, 41, 44, 16, 21, 22, 17, 12, 6] 

Edit: I see there are many alike questions like mine, I tried a solution from Sorting list based on values from another list, which is the following:

[x for _, x in sorted(zip(test, sort))]
[14, 43, 20, 29, 27, 16, 2, 44, 41, 40]

As it can be seen, this is not equal to my desired output as 20 should be on the first place.

martineau
  • 119,623
  • 25
  • 170
  • 301
Arnoldo Oliva
  • 103
  • 1
  • 9
  • 2
    Doing a web search for the title of your question yields many relevant results. [How much research effort is expected of Stack Overflow users?](//meta.stackoverflow.com/a/261593/843953) – Pranav Hosangadi Apr 06 '22 at 20:40
  • For the two of you, yes, I tried the solution of that and it didn't work out – Arnoldo Oliva Apr 06 '22 at 20:53
  • You want to change the order of the elements in `test` based on the elements of `matrix`, yes? If so you need `[x for _, x in sorted(zip(matrix, test))]` (notice `zip(matrix, test)` instead of what you did) What do you mean "sort test based on the matrix position"? It's not clear from your expected output how you want to sort the lists. – Pranav Hosangadi Apr 06 '22 at 21:01
  • 1
    You call it sorting, but the example output looks like you are filtering. I see no sorting going on with your example output. You've simply taken the contents of matrix, and moved the elements which are also found in `test`, to the front of the matrix. What about the rest? – smac89 Apr 06 '22 at 21:07
  • I re edited the post, I think it's more clear now – Arnoldo Oliva Apr 06 '22 at 21:13

1 Answers1

1

You can do this with list comprehension or looping over the matrix element to check each iteration if it belongs in the test array.

Example using list comprehension:

test = [16, 44, 12, 43, 17, 22, 6, 20, 41, 21]
matrix = [20, 40, 43, 41, 29, 2, 14, 27, 44, 16]

result = [i for i in matrix if i in test]

Example with normal append:

test = [16, 44, 12, 43, 17, 22, 6, 20, 41, 21]
matrix = [20, 40, 43, 41, 29, 2, 14, 27, 44, 16]

result = []
other = []

for i in matrix:
    if i in test:
        result.append(i)

    # Edit: if you want to keep the remaining ones in default sorting
    else:
        other.append(i)
result.extend(other)

Edit: updated the for loop to append everything not in test to another array. When the result array extend() that one, they would be combined. If this is what you're looking for, the list comprehension example here will not give the expected result.