1. 程式人生 > >python基本數據類型(四)-集合與運算符-python3筆記

python基本數據類型(四)-集合與運算符-python3筆記

python基本數據類型 集合與運算符 python3

1.集合

2.字典

3.運算符優先級

1.集合

創建:() set()     註意:創建空的集合要用set()
特點:元素唯一,無序
運算: &(交集)   |(並集)   -(差集)
方法:
s.add(x)    #添加單個元素
s.update()  #添加多個元素
s.remove()  #移除元素
s.clear()   #清空集合

#集合創建
    >>> se = {1,2,3}
    >>> print(type(se))
    <class ‘set‘>
    >>> se = {1,2,2,3}          #去重,唯一
    >>> print(se)
    {1, 2, 3}
    >>> se = {1,‘a‘,2,‘b‘}      #無序
    >>> se
    {1, 2, ‘a‘, ‘b‘}
#可hash的能放入集合
    >>> hash([1,2])
    Traceback (most recent call last):
      File "<pyshell#24>", line 1, in <module>
        hash([1,2])
    TypeError: unhashable type: ‘list‘
    >>> hash((a,2))
    Traceback (most recent call last):
      File "<pyshell#25>", line 1, in <module>
        hash((a,2))
    NameError: name ‘a‘ is not defined
    >>> hash((1,2))
    1299869600
    >>> hash(‘qwe‘)
    -917773703
    >>> a
    Traceback (most recent call last):
      File "<pyshell#28>", line 1, in <module>
        a
    NameError: name ‘a‘ is not defined
    >>> a=‘I love python‘
    >>> a
    ‘I love python‘
    >>> hash(a)
    -2061797837
    >>> 
#定義空集合(工廠模式定義集合)
    >>> se = set()
    >>> print(type(se))
    <class ‘set‘>
#集合的運算
    #屬於
    >>> a
    {1, 2, 3, 4, ‘a‘}
    >>> ‘a‘ in a
    True
    >>> ‘b‘ not in a
    True
    #延伸
    >>> se={1,2,3,4}
    >>> se2={3,4,5,6}
    >>> se < se2    #包含
    False
    >>> se <= se2   #包含
    False
    >>> se != se2   #不等於
    True

    #並集(兩個集合相加並去重)
    >>> se1={1,2,3};se2={2,3,4}
    >>> se1|se2
    {1, 2, 3, 4}
    #交集(取兩個集合重復的元素)
    >>> se1&se2
    {2, 3}
    #差集(前面的集合減去後面的集合元素重復的部分)
    >>> se1-se2
    {1}
    >>> se2-se1
    {4}
    #與非集(取各自集合獨立的部分)
    >>> se1^se2
    {1, 4}
#集合的基本方法
    查看集合的方法:
    >>> dir(se)
[‘__and__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__gt__‘, ‘__hash__‘, ‘__iand__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__ior__‘, ‘__isub__‘, ‘__iter__‘, ‘__ixor__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__ne__‘, ‘__new__‘, ‘__or__‘, ‘__rand__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__ror__‘, ‘__rsub__‘, ‘__rxor__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__sub__‘, ‘__subclasshook__‘, ‘__xor__‘, ‘add‘, ‘clear‘, ‘copy‘, ‘difference‘, ‘difference_update‘, ‘discard‘, ‘intersection‘, ‘intersection_update‘, ‘isdisjoint‘, ‘issubset‘, ‘issuperset‘, ‘pop‘, ‘remove‘, ‘symmetric_difference‘, ‘symmetric_difference_update‘, ‘union‘, ‘update‘]
    #添加單個元素(添加單個元素)
    >>> se={1,2}
    >>> se.add(3)
    >>> print(se)
    {1, 2, 3}
    #添加多個元素(添加多個元素(可叠代的對象))
    >>> se.update(‘4‘)
    >>> print(se)
    {1, 2, 3, ‘4‘}
    >>> se.update(‘456‘)
    >>> print(se)
    {1, 2, 3, ‘6‘, ‘4‘, ‘5‘}
    #移除元素(指定移除)
    >>> se.remove(‘5‘)
    >>> print(se)
    {1, 2, 3, ‘6‘, ‘4‘}
    #隨機移除
    >>> se.pop()
    1
    #清空集合
    >>> se.clear()
    >>> print(se)
    set()

2.字典

註:是python中唯一的一個映射類型
創建:{key:value}      #大括號創建字典的鍵時要加引號
dict{key=value}     #括號裏賦值方式,名字=對象,不要引號
字典裏的鍵和值用‘:’隔開,一對鍵和值組成一個項,項和項之間用‘,’隔開
特點:
鍵唯一,重復會被重新賦值
無序
key必須遵循python命名規則

添加和取值
    cidt[key]=value     #key存在則修改該值,沒有則添加
屬性方法:
.update({})     #在字典中添加多個項
.items()        #返回字典的各個項
.keys()         #返回字典的鍵
.values()       #返回字典的值
.get(k)         #如果鍵k在,返回k的值,不存在則返回None
.get(k,x)       #如果鍵k在,返回鍵k的值,不存在則返回x
.pop(k)         #返回並移除鍵k所對應的元素,不存在則拋出異常
.pop(k,x)       #返回並移除鍵k所對應的元素,不存在則返回x

總結:
    key唯一,故可以是數字,字符串,元祖

總結:
    可變對象: list set dict
    不可變對象: str tuple

#字典 唯一的映射類型,遵循hash,必須是不可變的對象
#定義字典
    >>> di={‘w‘:123,‘l‘:456,‘x‘:789}    
    >>> print(type(di))
    <class ‘dict‘>
    >>> di=dict(_i=123)
    >>> di
    {‘_i‘: 123}
    >>> print(type(di))
    <class ‘dict‘>
    >>> di={1:123,2:234}
    >>> print(type(di))
    <class ‘dict‘>
    >>> di1={‘e‘:[123,456]}
    >>> type(di1)
    <class ‘dict‘>
    >>> di2={‘e‘:(123,456)}
    >>> di3={‘e‘:‘123‘}
    >>> type(di3)
    <class ‘dict‘>
#定義空字典
    >>> di1=dict()          
    >>> print(type(di1))
    <class ‘dict‘>
 #字典取值(利用鍵取值)
     >>> di[1]
    123
    >>> di[2]
    234
 #字典修改
    >>> di[1]=‘qwe‘
    >>> di
    {1: ‘qwe‘, 2: 234}
 #添加key:value(在修改key值得時候,key存在即修改否則添加)
    >>> di[3]=890
    >>> di
    {1: ‘qwe‘, 2: 234, 3: 890}
    >>> di={‘q‘:1,‘w‘:2,(‘q‘,‘w‘):122}
    >>> di
    {‘q‘: 1, ‘w‘: 2, (‘q‘, ‘w‘): 122}
 #清空字典
     >>> di.clear()
    >>> print(di)
    {}
 #查看字典的屬性方法
     >>> dir(di)
    [‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘clear‘, ‘copy‘, ‘fromkeys‘, ‘get‘, ‘items‘, ‘keys‘, ‘pop‘, ‘popitem‘, ‘setdefault‘, ‘update‘, ‘values‘]
 #fromkeys
 #用給定的鍵建立新的字典,每個鍵默認為None(批量生產新的字典)
    >>> di.fromkeys({‘a‘,‘b‘,‘c‘})
    {‘b‘: None, ‘c‘: None, ‘a‘: None}
#用給定的鍵建立新的字典,每個鍵自定義為123
    >>> di.fromkeys({‘a‘,‘b‘,‘c‘},123)
    {‘b‘: 123, ‘c‘: 123, ‘a‘: 123}
>>> help(di.fromkeys)
Help on built-in function fromkeys:
fromkeys(iterable, value=None, /) method of builtins.type instance
    Returns a new dict with keys from iterable and values equal to value.
#字典取值;值存在,則返回值,不存在默認返回None,也可自定義
    >>> di
    {‘w‘: 123, ‘e‘: 456, ‘r‘: 789}
    >>> di.get(‘w‘)
    123
    >>> di.get(‘q‘)     
    >>> di
    {‘w‘: 123, ‘e‘: 456, ‘r‘: 789}
    >>> di.get(‘q‘,‘我不存在‘)
    ‘我不存在‘
#items,在列表中以元組的形式顯示字典的每一項
    >>> di.items()
    dict_items([(‘w‘, 123), (‘e‘, 456), (‘r‘, 789)])
    >>> list(di.items())    #查看字典的每一項
    [(‘w‘, 123), (‘e‘, 456), (‘r‘, 789)]
#以列表的形式查看字典的所有鍵
    >>> di.keys()
    dict_keys([‘w‘, ‘e‘, ‘r‘])
#以列表的形式查看字典的所有值
    >>> di.values()
    dict_values([123, 456, 789])
#pop,指定鍵,刪除對應的值。如果鍵不存在,可以自定義返回值
    >>> help(di.pop)
    Help on built-in function pop:
    pop(...) method of builtins.dict instance
        D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        If key is not found, d is returned if given, otherwise KeyError is raised
    >>> di
    {‘w‘: 123, ‘e‘: 456, ‘r‘: 789}
    >>> di.pop(‘e‘)
    456
    >>> di
    {‘w‘: 123, ‘r‘: 789}
    >>> di.pop(‘w‘,‘r‘)
    123
    >>> di
    {‘r‘: 789}
    >>> di.pop(‘q‘,‘我不存在‘)
    ‘我不存在‘
#popitem, 隨機刪除字典某一項(不需要對象)
    >>> di
    {‘r‘: 789, ‘w‘: 123}
    >>> di
    {‘r‘: 789, ‘w‘: 123}
    >>> di.popitem()
    (‘w‘, 123)
    >>> di
    {‘r‘: 789}
#類似get,存在返回值,不存在就更新到字典,對應的值默認為None,也可自定義
    >>> di.setdefault(‘r‘)
    789
    >>> di.setdefault(‘w‘,123)
    123
    >>> di
    {‘r‘: 789, ‘w‘: 123}
    >>> di.setdefault(‘q‘)
    >>> di
    {‘r‘: 789, ‘w‘: 123, ‘q‘: None
#將一個字典內容添加並更新覆蓋到原來的字典
    >>> di
    {‘r‘: 789, ‘w‘: 123, ‘q‘: None}
    >>> di1={‘p‘:234,‘q‘:123}
    >>> di.update(di1)
    >>> di
    {‘p‘: 234, ‘r‘: 789, ‘w‘: 123, ‘q‘: 123}    
    >>> di={‘x‘:[123,456]}
    >>> di
    {‘x‘: [123, 456]}
    >>> di[‘w‘]=123
    >>> di
    {‘x‘: [123, 456], ‘w‘: 123}

3.運算符

算數運算符: +,-,*,/,%,**,//
    賦值運算符: = += -= *= /= %= **=
    比較運算符: ==  !=  >  <  >=  <=
    成員運算符: in , not in
    身份運算符: is  , is not
        判斷兩個名字是否指向同一個對象,當id相同時返回True(==比較運算時判斷的值)
    邏輯運算符: and  or  not
        and(與)  兩個條件都滿足是才返回True
        or(或)   有一個條件滿足了就返回True
        not(非)  取反

    計算順序:默認,運算符優先級表決定了那個運算符在別的運算符之前計算。然而,如果你想改變它們的順序,你得使用圓括號
    結合規律:運算符通常由左向右結合,及具有相同優先級的運算符按照從左向右的順序計算
    **                          #冪運算
    = - * / %                   #算數運算符
    < > <= >=                   #比較運算符
    ==  !=                      #比較運算符
    = %= /= -= += *= **=        #賦值運算符
    is  is not                  #身份運算符
    in  not in                  #成員運算符
    not  >  and  > or           #邏輯運算符

>>> a=1;b=2
>>> a==b
False
>>> a!=b
True
>>> a is b
False
>>> a is not b
True
>>> a==1 and b==3
False
>>> a==1 or b==3
True
>>> not b==3
True
>>> a==1 and not b==3
True

python基本數據類型(四)-集合與運算符-python3筆記