gpt4 book ai didi

python - 按可以为 None 的属性对列表进行排序

转载 作者:IT老高 更新时间:2023-10-28 21:06:15 25 4
gpt4 key购买 nike

我正在尝试使用

对对象列表进行排序

my_list.sort(key=operator.attrgetter(attr_name))

但如果任何列表项具有 attr = None而不是 attr = 'whatever' ,

然后我得到一个 TypeError: unorderable types: NoneType() < str()

在 Py2 中这不是问题。我如何在 Py3 中处理这个问题?

最佳答案

排序比较运算符对 Python 3 中的类型更加严格,如 here 所述:

The ordering comparison operators (<, <=, >=, >) raise a TypeError exception when the operands don’t have a meaningful natural ordering.

Python 2 在任何字符串(甚至是空字符串)之前对 None 进行排序:

>>> None < None
False

>>> None < "abc"
True

>>> None < ""
True

在 Python 3 中,任何对 NoneType 实例进行排序的尝试都会导致异常:

>>> None < "abc"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: NoneType() < str()

我能想到的最快解决方法是将 None 实例显式映射为可排序的对象,例如 "":

my_list_sortable = [(x or "") for x in my_list]

如果你想在保持数据完整的同时对数据进行排序,只需给 sort 一个自定义的 key 方法:

def nonesorter(a):
if not a:
return ""
return a

my_list.sort(key=nonesorter)

关于python - 按可以为 None 的属性对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12971631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com