您需要在排序操作期间将价格和名称放在一起。这可以通过将它们组合在您排序的元组列表中(从价格开始)然后分配回字典项目来实现:
dictionaryofproduct={
"name":["Magnetic Adsorption Aluminum Bumper Case For Samsung Note 8","ESET Nod32 Antivirus","Other"],
"price":[1200,212,500]
}
prices,names = zip(*sorted(zip(dictionaryofproduct["price"],dictionaryofproduct["name"])))
dictionaryofproduct["price"] = list(prices)
dictionaryofproduct["name"] = list(names)
print(dictionaryofproduct)
{'name': ['ESET Nod32 Antivirus', 'Other', 'Magnetic Adsorption Aluminum Bumper Case For Samsung Note 8'],
'price': [212, 500, 1200]}
注意:我添加了一个“其他”产品以清楚地表明产品名称不只是按字母顺序排序
另一种方法是编写两个辅助函数来获取排序并将排序应用于多个相同大小的列表:
def getSortOrder(L,key=lambda v:v):
return sorted(range(len(L)),key=lambda i:key(L[i]))
def applySortOrder(L,order): L[:] = [L[i] for i in order]
orderByPrice = getSortOrder(dictionaryofproduct["price"])
applySortOrder(dictionaryofproduct["price"], orderByPrice)
applySortOrder(dictionaryofproduct["name"], orderByPrice)
顺便说一句,如果您不致力于此数据结构,您应该真正考虑将其更改为元组列表或字典列表,将每个产品的名称和价格放在一起,而不是依赖名称和价格处于相同的索引。如果您想使用这种模型,也可以查看 pandas/dataframes。