对值为对象 Python 的字典进行排序
Sorting a Dict whose values are objects Python
我有一个 dict
,其中的值是 Object
的 list
。
我需要根据对象的属性之一对它们进行排序。
{key1 : [(list1 of obj),(list2 of obj),(list3 of obj)], key2 : [(list1 of obj),(list2 of obj)]}
我需要按属性之一对 list
值进行排序,例如"Quantity".
我的代码结构是:
for objlist in mydict[key]:
sorted(objlist ,key=lambda k: (k.Quantity),reverse=True)
sorted(objlist , key=operator.itemgetter)
s = sorted(s, key = lambda x: (x[1], x[2]))
objlist.sort(key=operator.attrgetter("Quantity"), reverse=False)
objlist.sort(key = lambda x: x.Quantity)
我尝试了以上所有选项,但没有任何效果。
这里有一些示例代码供您参考
class Test():
def __init__(self,q):
self.Quantity = q
def __repr__(self):
return "<Class Test: Quantity=" + str(self.Quantity) + ">"
mydict = mydict = {"a":[ Test(3), Test(2), Test(4)], "b": [Test(8), Test(10), Test(6)], "c":[Test(14), Test(12), Test(20)]}
print "Before Sort"
for key in mydict:
print (key,mydict[key])
dict_with_sorted_list = {}
for key in mydict:
dict_with_sorted_list[key] = sorted(mydict[key], key=lambda k: k.Quantity, reverse=True)
print "After Sort"
for key in dict_with_sorted_list:
print (key,dict_with_sorted_list[key])
如果您只是将排序后的列表分配回原始字典,您还可以使用列表对象的 sort()
方法对每个列表进行就地排序,避免创建新列表。用法类似于sorted()
。因为您不是在创建新列表,所以 sort()
方法比使用 sorted()
快一点点。在实践中,它通常不会有太大区别,除非您发现需要优化并且这是一个关键点。
>>> # Python 3.x
... from random import randint
>>>
>>> class Test(object):
... # Borrowed from the accepted answer.
... def __init__(self, q):
... self.Quantity = q
... def __repr__(self):
... return "<Class Test: Quantity=%d>" % self.Quantity
...
>>> keys = 'a b c'.split()
>>> my_dict = {key: [Test(randint(0, 50)) for _ in range(3)] for key in keys}
>>> print("Before sorting:")
Before sorting:
>>> for key in keys:
... print("%s" % my_dict[key])
...
[<Class Test: Quantity=13>, <Class Test: Quantity=49>, <Class Test: Quantity=9>]
[<Class Test: Quantity=30>, <Class Test: Quantity=3>, <Class Test: Quantity=6>]
[<Class Test: Quantity=29>, <Class Test: Quantity=33>, <Class Test: Quantity=37>]
>>> for key in keys:
... my_dict[key].sort(key=lambda k: k.Quantity, reverse=True)
...
>>> print("After sorting:")
After sorting:
>>> for key in keys:
... print("%s" % my_dict[key])
...
[<Class Test: Quantity=49>, <Class Test: Quantity=13>, <Class Test: Quantity=9>]
[<Class Test: Quantity=30>, <Class Test: Quantity=6>, <Class Test: Quantity=3>]
[<Class Test: Quantity=37>, <Class Test: Quantity=33>, <Class Test: Quantity=29>]
>>>
我有一个 dict
,其中的值是 Object
的 list
。
我需要根据对象的属性之一对它们进行排序。
{key1 : [(list1 of obj),(list2 of obj),(list3 of obj)], key2 : [(list1 of obj),(list2 of obj)]}
我需要按属性之一对 list
值进行排序,例如"Quantity".
我的代码结构是:
for objlist in mydict[key]:
sorted(objlist ,key=lambda k: (k.Quantity),reverse=True)
sorted(objlist , key=operator.itemgetter)
s = sorted(s, key = lambda x: (x[1], x[2]))
objlist.sort(key=operator.attrgetter("Quantity"), reverse=False)
objlist.sort(key = lambda x: x.Quantity)
我尝试了以上所有选项,但没有任何效果。
这里有一些示例代码供您参考
class Test():
def __init__(self,q):
self.Quantity = q
def __repr__(self):
return "<Class Test: Quantity=" + str(self.Quantity) + ">"
mydict = mydict = {"a":[ Test(3), Test(2), Test(4)], "b": [Test(8), Test(10), Test(6)], "c":[Test(14), Test(12), Test(20)]}
print "Before Sort"
for key in mydict:
print (key,mydict[key])
dict_with_sorted_list = {}
for key in mydict:
dict_with_sorted_list[key] = sorted(mydict[key], key=lambda k: k.Quantity, reverse=True)
print "After Sort"
for key in dict_with_sorted_list:
print (key,dict_with_sorted_list[key])
如果您只是将排序后的列表分配回原始字典,您还可以使用列表对象的 sort()
方法对每个列表进行就地排序,避免创建新列表。用法类似于sorted()
。因为您不是在创建新列表,所以 sort()
方法比使用 sorted()
快一点点。在实践中,它通常不会有太大区别,除非您发现需要优化并且这是一个关键点。
>>> # Python 3.x
... from random import randint
>>>
>>> class Test(object):
... # Borrowed from the accepted answer.
... def __init__(self, q):
... self.Quantity = q
... def __repr__(self):
... return "<Class Test: Quantity=%d>" % self.Quantity
...
>>> keys = 'a b c'.split()
>>> my_dict = {key: [Test(randint(0, 50)) for _ in range(3)] for key in keys}
>>> print("Before sorting:")
Before sorting:
>>> for key in keys:
... print("%s" % my_dict[key])
...
[<Class Test: Quantity=13>, <Class Test: Quantity=49>, <Class Test: Quantity=9>]
[<Class Test: Quantity=30>, <Class Test: Quantity=3>, <Class Test: Quantity=6>]
[<Class Test: Quantity=29>, <Class Test: Quantity=33>, <Class Test: Quantity=37>]
>>> for key in keys:
... my_dict[key].sort(key=lambda k: k.Quantity, reverse=True)
...
>>> print("After sorting:")
After sorting:
>>> for key in keys:
... print("%s" % my_dict[key])
...
[<Class Test: Quantity=49>, <Class Test: Quantity=13>, <Class Test: Quantity=9>]
[<Class Test: Quantity=30>, <Class Test: Quantity=6>, <Class Test: Quantity=3>]
[<Class Test: Quantity=37>, <Class Test: Quantity=33>, <Class Test: Quantity=29>]
>>>