码迷,mamicode.com
首页 > 其他好文 > 详细

字典dict,zip()

时间:2017-12-20 13:38:38      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:log   nbsp   pos   5.5   最大   empty   max   排列   seq   

problem: 怎样在数据字典中执行一些计算操作(比如求最小值、最大值、排序等等)?

answer

    eg1:

 

                考虑下面的股票名和价格映射字典:

                  prices = {‘ACME‘: 45.23,‘AAPL‘: 612.78,‘IBM‘: 205.55,‘HPQ‘: 37.20,‘FB‘: 10.75}

                  为了对字典值执行计算操作,通常需要使用zip()函数先将键和值反转过来.下面是查找最小和最大股票价格和股票值的代码:


        min_price = min(zip(prices.values(), prices.keys()))
                          # min_price is (10.75, ‘FB‘)
                          max_price = max(zip(prices.values(), prices.keys()))
                          # max_price is (612.78, ‘AAPL‘)


                  类似的,可以使用zip() 和sorted() 函数来排列字典数据:


                        prices_sorted = sorted(zip(prices.values(), prices.keys()))
                        # prices_sorted is [(10.75, ‘FB‘), (37.2, ‘HPQ‘),
                        # (45.23, ‘ACME‘), (205.55, ‘IBM‘),
                        # (612.78, ‘AAPL‘)]

 

                  执行这些计算的时候,需要注意的是zip() 函数创建的是一个只能访问一次的迭代器。比如,下面的代码就会产生错误:

                           prices_and_names = zip(prices.values(), prices.keys())
                           print(min(prices_and_names)) # OK
                           print(max(prices_and_names)) # ValueError: max() arg is an empty sequence

    eg2:

 

               字典值相同,键不同,比较值的大小

                    >>> prices = { ‘AAA‘ : 45.23, ‘ZZZ‘: 45.23 }
                    >>> min(zip(prices.values(), prices.keys()))
                    (45.23, ‘AAA‘)
                   >>> max(zip(prices.values(), prices.keys()))
                   (45.23, ‘ZZZ‘)

字典dict,zip()

标签:log   nbsp   pos   5.5   最大   empty   max   排列   seq   

原文地址:http://www.cnblogs.com/baxianhua/p/8072824.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!