问题:在字典上对数据执行各式各样的计算(比如求最小值、最大值、排序)。
解决方案:利用zip()将字典的键-值对“反转”为值-键对序列。
例如:如下字典存放的股票名称和对应的价格:
>>> prices = { ‘ACME‘: 45.23, ‘AAPL‘: 612.78, ‘IBM‘: 205.55, ‘HPQ‘: 37.20, ‘FB‘: 10.75 } >>> prices {‘HPQ‘: 37.2, ‘IBM‘: 205.55, ‘FB‘: 10.75, ‘ACME‘: 45.23, ‘AAPL‘: 612.78} >>> min_price = min(zip(prices.values(), prices.keys())) #注意zip(x,y)中参数的顺序 >>> max_price = max(zip(prices.values(), prices.keys())) >>> min_price (10.75, ‘FB‘) >>> max_price (612.78, ‘AAPL‘) >>> prices_sorted = sorted(zip(prices.values(), prices.keys())) >>> prices_sorted [(10.75, ‘FB‘), (37.2, ‘HPQ‘), (45.23, ‘ACME‘), (205.55, ‘IBM‘), (612.78, ‘AAPL‘)]
>>> min_price2 = min(zip(prices)) #错误用法 >>> min_price2 (‘AAPL‘,) >>> max_price2 = max(zip(prices)) #错误用法 >>> max_price2 (‘IBM‘,) >>> min_price3 = min(zip(prices.keys(), prices.values())) #zip()参数顺序不对,获取错误的值 >>> min_price3 (‘AAPL‘, 612.78) >>> max_price3 = max(zip(prices.keys(), prices.values())) #zip()参数顺序不对,获取错误的值 >>> max_price3 (‘IBM‘, 205.55) >>>
进行这些计算时,请注意zip()创建了一个迭代器,它的内容只能消费一次。例如:
>>> pirces_and_names=zip(prices.values(), prices.keys()) >>> pirces_and_names <zip object at 0x023BDFA8> >>> min(pirces_and_names) (10.75, ‘FB‘) >>> max(pirces_and_names) Traceback (most recent call last): File "<pyshell#25>", line 1, in <module> max(pirces_and_names) ValueError: max() arg is an empty sequence >>>
注意:当涉及(value,key)对的比较时,碰巧有多个条目拥有相同的value值,那么此时key将用来作为判定结果的依据。
>>> 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‘) >>>
时间: 2024-10-10 03:14:38