首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将无值推送到末尾时对列表进行排序

将无值推送到末尾时对列表进行排序
EN

Stack Overflow用户
提问于 2013-08-24 04:45:55
回答 3查看 28.1K关注 0票数 63

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

代码语言:javascript
复制
>>> 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方式对列表进行排序,但列表末尾没有任何值,就像这样:

代码语言:javascript
复制
[1, 2, 3, 4, 5, 7, None]

我觉得这里可以使用"key“参数的一些技巧

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-08-24 04:48:52

代码语言:javascript
复制
>>> 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开始),然后按值排序。

票数 160
EN

Stack Overflow用户

发布于 2013-08-24 04:48:17

试试这个:

代码语言:javascript
复制
sorted(l, key=lambda x: float('inf') if x is None else x)

因为无穷大比所有整数都大,所以None总是放在最后。

票数 20
EN

Stack Overflow用户

发布于 2018-06-06 20:47:49

我创建了一个函数,扩展了Andrew Clark的答案和tutuDajuju的评论。

代码语言:javascript
复制
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)

下面是一个如何运行它的示例:

代码语言:javascript
复制
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))
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18411560

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档