Last active
August 5, 2020 22:53
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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