python - 在 Python3 中对具有 None 值的元组列表进行排序

标签 python python-3.x python-2.x

<分区>

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

如果不存在任何值,这种比较变化会导致难以对元组列表进行排序。

在 Python 2 中:

>>> unordered_list = [('3', '1', None), ('3','1', '4'), ('3', '1', None)]
>>> sorted(unordered_list, reverse=True)

[('3', '1', '4'), ('3', '1', None), ('3', '1', None)]

在 Python 3 中:

>>> unordered_list = [('3', '1', None), ('3','1', '4'), ('3', '1', None)]
>>> sorted(unordered_list, reverse=True)

TypeError: unorderable types: str() < NoneType()

您是否知道如何以优雅的方式使用 Python 2 实现相同的行为?

注意:在上面的例子中我有整数,但这只是一个例子。元组的元素将具有相同的类型,并且它们可以是任何类型。

ex.2 [('test3','test1', 'test4'), ('test3', 'test1', None)]
ex.3 [( 3, 1, 4), (3, 1, None)]
ex.4 [( 3.1, 1.1, 4.1), (3.1, 1.1, None)]

最佳答案

在这种情况下,您可以使用自定义键函数将所有 None 转换为空字符串,例如:

sorted(unordered_list, key=lambda L: tuple(el or '' for el in L), reverse=True)

它会给你:

[('3', '1', '4'), ('3', '1', None), ('3', '1', None)]

关于python - 在 Python3 中对具有 None 值的元组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60695318/

相关文章:

python - argparse 错误 : Option not recognized

python - Windows中是否有等效的evdev

python - 在 Python 2 和 3 中导入包内和包外都有效的结构?

python - 使 python 3 异常向后兼容

python - 在 Python 中从中文到 Latin1 的字符编码

python - Twisted - 在子进程中使用 adoptStreamConnection 后,如何告诉 react 器处理协议(protocol)对象?

python - Azure Functions Python blobTrigger 如何修复 "Microsoft.Azure.WebJobs.Extensions.Storage: Object reference not set to an instance of an object."?

python - App Engine 1.8.4 引发 AttributeError 将文档放入搜索索引

python - 属性错误 : module 'regex' has no attribute 'Pattern'

python - 保存到 Parquet 会在 Dask.dataframe 中引发错误