如何按成员变量
对dictiony进行排序class Item():
def __init__(self, _name, _index, _price):
self.name = _name
self.index = _index
self.price = _price
我想显示按索引或价格排序的商品信息。
DicItems = {}
DicItems["Candy"] = Item("Candy", 1, 100)
DicItems["IceCream"] = Item("IceCream", 2, 500)
DicItems["Snack"] = Item("Snack", 3, 300)
按索引打印项目列表顺序 - >导致
Candy 1 100
IceCream 2 500
Snack 3 300
按价格打印商品清单 - >导致
Candy 1 100
Snack 3 300
IceCream 2 500
答案 0 :(得分:1)
准备代码:
class Item():
def __init__(self, _name, _index, _price):
self.name = _name
self.index = _index
self.price = _price
def items(self):
return self.name, self.index, self.price
d = {}
d["Candy"] = Item("Candy", 1, 100)
d["IceCream"] = Item("IceCream", 2, 500)
d["Snack"] = Item("Snack", 3, 300)
排序代码:
print [item.items() for item in sorted(d.values(), key = lambda x:x.index)]
print [item.items() for item in sorted(d.values(), key = lambda x:x.price)]
<强>输出强>
[('Candy', 1, 100), ('IceCream', 2, 500), ('Snack', 3, 300)]
[('Candy', 1, 100), ('Snack', 3, 300), ('IceCream', 2, 500)]
或者我们可以使用attrgetter来概括它
from operator import attrgetter
def sorter(d, key):
return [item.items() for item in sorted(d.values(), key = attrgetter(key))]
print sorter(d, "index")
print sorter(d, "name")
print sorter(d, "price")
<强>输出强>
[('Candy', 1, 100), ('IceCream', 2, 500), ('Snack', 3, 300)]
[('Candy', 1, 100), ('IceCream', 2, 500), ('Snack', 3, 300)]
[('Candy', 1, 100), ('Snack', 3, 300), ('IceCream', 2, 500)]
答案 1 :(得分:0)
python中的字典没有任何顺序。
根据您的需要,可以通过以下方式实现:
from operator import attrgetter
name_getter = attrgetter('name')
index_getter = attrgetter('index')
price_getter = attrgetter('price')
sorted_by_index = sorted(DicItems, key=index_getter)
sorted_by_name = sorted(DicItems, key=name_getter)
sorted_by_price = sorted(DicItems, key=price_getter)
答案 2 :(得分:0)
更难,但更普遍
from operator import attrgetter
class DictItems(dict):
def sortByPrice():
return sorted(self.values(), key=attrgetter('price'))
def sortByIndex():
return sorted(self.values(), key=attrgetter('index'))
d = DictItems()
d["Candy"] = Item("Candy", 1, 100)
d["IceCream"] = Item("IceCream", 2, 500)
d["Snack"] = Item("Snack", 3, 300)
d.sortByPrice()
d.sortByIndex()