我试图弄清楚如何用值(这些值是元组)创建字典的排序表示形式,并在Python3,中的值上使用自定义比较器()。
我读过这些话题,但我仍然在挣扎:
作为的一个特定示例,可以将我试图解决的问题考虑为:“获得按总成本排序的产品列表,给定包含客户在结帐中包含的产品(键)的字典,以及每个产品的数量和成本(以二元组形式存储)。在python 2中,您可以使用以下内容:
checkout_dict = {'Apples': (1, 3), 'Oranges': (3, 3), 'Grapes': (7, 1),
'Cheese': (10, 1), 'Crackers': (4, 4)}
from operator import itemgetter
def sort_dict(dict, comparison_func):
return sorted(dict.iteritems(), key=itemgetter(1),
cmp=comparison_func)
def cmp_total_cost(product_data_1, product_data_2):
total_product_cost_1 = (product_data_1[0]) * (product_data_1[0])
total_product_cost_2 = (product_data_2[0]) * (product_data_2[0])
return total_product_cost_2 - total_product_cost_1
print sort_dict(checkout_dict, cmp_total_cost)预期的输出如下所示:
[('Crackers', (4, 4)), ('Cheese', (10, 1)), ('Oranges', (3, 3)),
('Grapes', (7, 1)), ('Apples', (1, 3))]但是,在Python3中,sorted的sorted参数被否决了,相反,我们需要将行为作为key参数的一部分。
我知道我们需要使用像模块这样的东西,但是我不能把我的头脑集中在如何保持所有事物的泛化上。我对如何将itemgetter(1)与cmp_to_key函数和自定义比较函数组合起来感到困惑。
另外,我了解到,通过上面的例子,我可以简单地先遍历字典,然后计算总成本,然后进行排序,但是我正在寻找一个通用的解决方案--我可以应用于许多不同类型的比较。
Note
我也希望这是尽可能的表演。我发现了一些信息,使用operator.itemgetter确实可以帮助加快速度:在Python中按值排序字典(改进了?)
发布于 2017-05-14 14:56:44
如果您只想得到一个元组的列表,按照第一个元素的顺序乘以第二个元素,这就可以了:
sorted(checkout_dict.items(), key=lambda item: item[1][0] * item[1][1])
# [('Apples', (1, 3)), ('Grapes', (7, 1)), ('Oranges', (3, 3)), ('Cheese', (10, 1)),
# ('Crackers', (4, 4))]
# or in the other way around
sorted(checkout_dict.items(), key=lambda item: item[1][0] * item[1][1], reverse=True)
# [('Crackers', (4, 4)), ('Cheese', (10, 1)), ('Oranges', (3, 3)), ('Grapes', (7, 1)),
# ('Apples', (1, 3))]https://stackoverflow.com/questions/43965164
复制相似问题