今天學dict & set
1. dict就是字典(dictionary), 是使用Key-value去對應.
>>> dict = {'A': 1, 'B': 2, 'c': 3}
>>> dict
{'A': 1, 'B': 2, 'c': 3}
>>> dict ['B']
2
>>>
2. 新增Key-value
>>> dict ['D'] = 4
>>> dict ['D']
4
>>>
3. 替換value: 一個Key只能對應一個value, 故新的value會覆蓋之前的舊value.
>>> dict ['D'] = 5
>>> dict ['D']
5
>>> dict ['D'] = 6
>>> dict ['D']
6
>>>
4. 刪除Key: 使用pop(key)的方式
>>> dict.pop('D')
6
>>> dict
{'a': 1, 'B': 2, 'c': 3}
>>>
5. set跟dict很像, 但只有key, 沒有value.
>>> s = set([1, 2, 3])
>>> s
{1, 2, 3}
>>>
6. add(key): 可以增加新元素到set中, 可以重複, 但沒效果.
>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>>
7. 刪除元素: remove(key)
>>> s.remove(4)
>>> s
{1, 2, 3}
>>>
8. 兩個set的數學上的交集
>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>>
9. 兩個set的數學上的並集, 因為set不會重複元素
>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 | s2
{1, 2, 3, 4}
>>>
Example
#20170515
# -*- coding: utf-8 -*-
#08_01.py
#把(1,2,3)放進dict
dict = {'Cisco':1, 'GDC':2, 'Peter':3}
key =(1,2,3)
dict [key] = 4
print (key)
print (dict)
#把(1,2,3)放進set
s = set (['cisco', 'gdc', 'peter'])
key = (1,2,3)
s.add(key)
print (key)
print (s)
最初發表 / 最後更新: 2017.05.15 / 2018.05.29
0 comments:
張貼留言