结尾没有的Python排序列表

2024-05-15 17:42:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个没有对象的同类列表,但是它可以包含任何类型的值。 示例:

>>> l = [1, 3, 2, 5, 4, None, 7]
>>> sorted(l)
[None, 1, 2, 3, 4, 5, 7]
>>> sorted(l, reverse=True)
[7, 5, 4, 3, 2, 1, None]

有没有一种方法可以不用重新设计轮子,让列表按通常的python方式排序,但是列表末尾没有任何值,比如:

[1, 2, 3, 4, 5, 7, None]

我觉得这里有一些关键参数的技巧


Tags: 对象方法nonetrue示例类型列表排序
3条回答

我创建了一个函数来扩展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))

试试这个:

sorted(l, key=lambda x: float('inf') if x is None else x)

由于无穷大大于所有整数,None将始终放在最后。

>>> l = [1, 3, 2, 5, 4, None, 7]
>>> sorted(l, key=lambda x: (x is None, x))
[1, 2, 3, 4, 5, 7, None]

这将为列表中的每个元素构造一个元组,如果值是None,则为(True, None)的元组,如果值是其他值,则为(False, x)(其中x是值)。由于元组是按项排序的,这意味着所有非None元素都将首先出现(因为False < True),然后按值排序。

相关问题 更多 >