Skip to content

Instantly share code, notes, and snippets.

@westc
Last active August 5, 2020 22:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westc/1c26757926c0231c7e1d58df0f8184af to your computer and use it in GitHub Desktop.
Save westc/1c26757926c0231c7e1d58df0f8184af to your computer and use it in GitHub Desktop.
Order (or sort) one list the same way that a second list is ordered. Orders multiple identical values correctly.
def orderLike(unordered:list, ordered:list):
"""
Takes 2 lists where the first list is the unordered list that should be
ordered similar to the second list which is in the correct order. This
solution handles identical values appearing in the ordered list. Returns a
new list without modifying the lists that were passed in.
"""
result = []
unordered = unordered[:]
for ordered_value in ordered:
# Check for non-NaN values
if ordered_value in unordered:
unordered.pop(unordered.index(ordered_value))
result.append(ordered_value)
# Check for NaN
elif ordered_value != ordered_value:
for i, v in enumerate(unordered):
if v != v:
unordered.pop(i)
result.append(v)
break
return result + unordered
from orderLike import orderLike
unordered = [float('nan'), 4, 5, 2, float('nan')]
ordered = [1, 2, 3, 5, 7, float('nan')]
print(orderLike(unordered, ordered))
# [2, 5, nan, 4, nan]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment