我创建了一个函数,扩展了 Andrew Clark 的答案和 tutuDajuju 的评论。
def sort(myList, reverse = False, sortNone = False):
"""Sorts a list that may or may not contain None.
Special thanks to Andrew Clark and tutuDajuju for how to sort None on https://stackoverflow.com/questions/18411560/python-sort-list-with-none-at-the-end
reverse (bool) - Determines if the list is sorted in ascending or descending order
sortNone (bool) - Determines how None is sorted
- If True: Will place None at the beginning of the list
- If False: Will place None at the end of the list
- If None: Will remove all instances of None from the list
Example Input: sort([1, 3, 2, 5, 4, None, 7])
Example Input: sort([1, 3, 2, 5, 4, None, 7], reverse = True)
Example Input: sort([1, 3, 2, 5, 4, None, 7], reverse = True, sortNone = True)
Example Input: sort([1, 3, 2, 5, 4, None, 7], sortNone = None)
"""
return sorted(filter(lambda item: True if (sortNone != None) else (item != None), myList),
key = lambda item: (((item is None) if (reverse) else (item is not None)) if (sortNone) else
((item is not None) if (reverse) else (item is None)), item),
reverse = reverse)
这是一个如何运行它的示例:
myList = [1, 3, 2, 5, 4, None, 7]
print(sort(myList))
print(sort(myList, reverse = True))
print(sort(myList, sortNone = True))
print(sort(myList, reverse = True, sortNone = True))
print(sort(myList, sortNone = None))
print(sort(myList, reverse = True, sortNone = None))