字典与集合
1.字典是Python唯一的映射集,标志性符号是{}
>>> dict1={'李宁':'一切皆有可能','耐克':'just do it','阿迪':'nothing is impossible'}
>>> print ('李宁的口号是:',dict1['李宁'])
李宁的口号是: 一切皆有可能
>>> dict2={1:'one',2:'two',3:'three'}
>>> dict2[2]
'two'
2.创建字典的方法
>>> dict3=dict((('F',70),('i',105),('s',115)))
>>> dict3
{'F': 70, 'i': 105, 's': 115}
>>> dict4=dict(小甲鱼='让编程改变世界',苍井空='让')
>>> dict4
{'小甲鱼': '让编程改变世界', '苍井空': '让'}
3.fromkeys()
>>> dict1={}
>>> dict1.fromkeys((1,2,3))
{1: None, 2: None, 3: None}
>>> dict1.fromkeys((1,2,3),'number')
{1: 'number', 2: 'number', 3: 'number'}
>>> dict1.fromkeys((1,2,3),('one','two','three'))
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
>>> dict1.fromkeys((1,3),'数字')
{1: '数字', 3: '数字'}
4.访问字典的方法
- keys()
>>> dict1=dict1.fromkeys(range(32),'赞')
>>> dict1
{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞', 5: '赞', 6: '赞', 7: '赞', 8: '赞', 9: '赞', 10: '赞', 11: '赞', 12: '赞', 13: '赞', 14: '赞', 15: '赞', 16: '赞', 17: '赞', 18: '赞', 19: '赞', 20: '赞', 21: '赞', 22: '赞', 23: '赞', 24: '赞', 25: '赞', 26: '赞', 27: '赞', 28: '赞', 29: '赞', 30: '赞', 31: '赞'}
>>> for eachkey in dict1.keys():
print (eachkey)
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
- values()
>>> for eachvalue in dict1.values():
print (eachvalue)
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
- items()
>>> for eachitem in dict1.items():
print (eachitem)
(0, '赞')
(1, '赞')
(2, '赞')
(3, '赞')
(4, '赞')
(5, '赞')
(6, '赞')
(7, '赞')
(8, '赞')
(9, '赞')
(10, '赞')
(11, '赞')
(12, '赞')
(13, '赞')
(14, '赞')
(15, '赞')
(16, '赞')
(17, '赞')
(18, '赞')
(19, '赞')
(20, '赞')
(21, '赞')
(22, '赞')
(23, '赞')
(24, '赞')
(25, '赞')
(26, '赞')
(27, '赞')
(28, '赞')
(29, '赞')
(30, '赞')
(31, '赞')
5.清空一个字典
dict1.clear()
dict1
{}
6.copy方法
>>> a={1:'one',2:'two'}
>>> b=a.copy()
>>> b
{1: 'one', 2: 'two'}
>>> c=a
>>> c
{1: 'one', 2: 'two'}
>>> id(a)
2599778465040
>>> id(b)
2599779969712
>>> id(c)
2599778465040
>>> c[4]='four'
>>> c
{1: 'one', 2: 'two', 4: 'four'}
>>> a
{1: 'one', 2: 'two', 4: 'four'}
>>> b
{1: 'one', 2: 'two'}
7.pop和popitem
>>> a.pop(2)
'two'
>>> a
{1: 'one', 4: 'four'}
>>> a.popitem()
(4, 'four')
>>> a
{1: 'one'}
8.集合(set),唯一,集合是无序的,不支持索引
9.创建一个集合
-
直接把一堆元素用{}括起来
-
使用set()工厂函数
>>> set1=set([1,2,3])
>>> set1
{1, 2, 3}
>>> num2=[1,2,3,3,2,1]
>>> num2
[1, 2, 3, 3, 2, 1]
>>> num2=list(set(num2))
>>> num2
[1, 2, 3]
用set函数得到的集合是无序的
10.不可变集合
>>> num3=frozenset([1,2,3,4,5])
>>> num3
frozenset({1, 2, 3, 4, 5})
>>> num3.add(0)
Traceback (most recent call last):
File "<pyshell#60>", line 1, in <module>
num3.add(0)
AttributeError: 'frozenset' object has no attribute 'add'