我有一些自定义对象和字典需要排序。我希望同时对对象和字典进行排序。我想通过属性对对象进行排序,通过键对字典进行排序。
object.name = 'Jack'
d = {'name':'Jill'}
sort_me =[object, d]
我该如何使用对象的名称属性和字典的“name”键来对此列表进行排序?
import types
class obj(object):
def __init__(self, arg):
self.name = arg
def extract_name(obj):
if type(obj) is types.DictType:
return obj['name']
else:
return obj.__dict__['name']
d = { 'name': 'Jill'}
print sorted([obj('Jack'), d], key=extract_name)
def extract_elem_v2(elem_name):
def key_extractor(obj):
dct = obj if isinstance(obj, dict) else obj.__dict__
return dct[elem_name]
return key_extractor
您可以这样使用:
print sorted(list_of_stuff, key=extract_elem_v2('name'))
sort_me.sort(key=attr_or_itemgetter('name'))
attr_or_itemgetter()
函数的作用:
class attr_or_itemgetter(object):
def __init__(self, name):
self.name = name
def __call__(self, obj):
try: return getattr(obj, name)
except AttributeError:
return obj[name]
注意:该函数故意不检查字典类型,因此将 attr_or_itemgetter('items')
应用于字典将返回 dict.items
方法。
sort()
不会返回排序后的列表,但是sorted()
会返回,因此如果您想将其传递给模板,则应在参数中使用sorted
,或者在将列表作为参数传递之前使用sort
。itemized_action_list = list(chain(detection_point.insertbodyaction_set.all(),
detection_point.insertheaderaction_set.all(),
detection_point.modifybodyaction_set.all(),
detection_point.modifyheaderaction_set.all(),
detection_point.removebodyaction_set.all(),
detection_point.removeheaderaction_set.all(),
detection_point.redirectaction_set.all()))
sorted(itemized_action_list, key=attrgetter('priority'))
新列表 = [10,"m",20,30,"a","r",70,"d"]
def 函数名(x):
if type(x) == str:
return ord(x)+100
return x
new_list.sort(key=func)
打印(new_list)
[10, 20, 30, 70, 'a', 'd', 'm', 'r']
isinstance(obj, dict)
更加简洁,也允许从dict
派生的类。 - RichieHindle__dict__
属性。 - jfstype(..) is
这个东西没有任何保留的价值。 B)vars(obj)
是否比obj.__dict__
更受欢迎?(vars 是一个不太知名的内置函数。) - u0b34a0f6ae