码迷,mamicode.com
首页 > 编程语言 > 详细

python进阶(数据结构和算法[三])

时间:2015-05-11 13:03:21      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:


在字典上将键映射到多个值上

一键多值字典

d = {‘a‘:[1,2,3], ‘b‘:[4,5]}
e = {‘a‘:{1,2,3}, ‘b‘:{4,5}}

可以使用from collections import defaultdict使用默认字典类,它的一个特点是自动初始化第一个值,后面只需要关注添加元素即可。

from collections import defaultdict
d = defaultdict(list)
d[‘a‘].append(1)
d[‘a‘].append(4)
.
.
.

d = defaultdict(set)
d[‘a‘].add(5)
.
.
.

使用范例:

d = defaultdict(list)
for key, value in pairs:
    d[key].append(value)

让字典保持有序

from collections import OrderedDict
d = OrderedDict()

d[‘grok‘] = 4
d[‘foo‘] = 1
d[‘abr‘] = 2

for key in d:
    print(key, d[key])

输出:

grok 4
foo 1
abr 2

对字典做迭代时,它会严格按照元素初始添加顺序进行。

与字典有关的计算问题

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()))
max_price = max(zip(prices.values(), prices.keys()))
print(min_price)
print(max_price)

# 要排序只要使用sorted函数即可

price_sorted = sorted(zip(prices.values(), prices.keys()))

for key, value in price_sorted:
    print(key, value)

输出:

(10.75, ‘FB‘)
(612.78, ‘AAPL‘)
10.75 FB
37.2 HPQ
45.23 ACME
205.55 IBM
612.78 AAPL

我们看一下如果不使用zip(),效果会怎么样?

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

print(min(prices)) #只会查找键

print(min(prices.values())) # 只查找值,不能映射到键上

//附加

prices = {‘AAA‘:34, ‘BBB‘:34}

print(min(zip(prices.values(), prices.keys()))) #反转之后当值相等的时候,再比较值的大小

在两个字典中寻找相同点

a = {
   ‘x‘ : 1,
   ‘y‘ : 2,
   ‘z‘ : 3
}

b = {
   ‘w‘ : 10,
   ‘x‘ : 11,
   ‘y‘ : 2
}

print(‘Common keys:‘, a.keys() & b.keys())
print(‘Keys in a not in b:‘, a.keys() - b.keys())
print(‘(key,value) pairs in common:‘, a.items() & b.items()

输出:

Common keys: {‘y‘, ‘x‘}
Keys in a not in b: {‘z‘}
(key,value) pairs in common: {(‘y‘, 2)}

python进阶(数据结构和算法[三])

标签:

原文地址:http://blog.csdn.net/yapian8/article/details/45641905

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