【发布时间】:2018-12-12 16:21:24
【问题描述】:
我正在使用 Python 3 的 operator 模块中的 attrgetter 函数来对对象列表(命中)进行排序。每个对象都有 12 个属性,我的排序函数可以输入其中的任何一个,以便以任何需要的方式对列表进行排序。我有兴趣排序的属性包含字符串。这是我代码中的相关 sn-p。
from operator import attrgetter
...
def sort_hits_by_attribute(hits, attribute, backwards = False):
"""Takes a lits of hits and sorts them by some attribute.
"""
return sorted(hits, key = attrgetter(attribute), reverse = backwards)
这是一个“命中”对象及其属性的示例。
name: ...
entity_1: coffee cultivation
entity_2: ...
full_statement: ...
category: ...
rule: ...
syn_configs: ...
lex_conditions: ...
sentence_number: ...
close_call: False
message: ...
id: 119
如果我按属性entity_1 对对象列表进行排序,那么上述对象将在 一个其entity_1 字段以大写字母开头的实例之后进行排序:例如,“咖啡”甚至是“动物园”。
我想使用类似casefold() 的函数,以便将大写字母与小写字母相邻并在其之后排序。但是casefold() 只对字符串有效,所以使用key = attrgetter(attribute).casefold() 会返回一个AttributeError。
我怎样才能保留sort_hits_by_attribute() 的功能——即按函数调用期间传入的属性进行排序——但在这样做时强制 Python 使用不同的排序 {aAbBcCdDeE...}?
【问题讨论】:
标签: python sorting attributes case-sensitive case-insensitive