python基礎資料型別 (Elementary Data Type)(四)-集合與運算子-python3筆記

來源:互聯網
上載者:User

標籤:python基礎資料型別 (Elementary Data Type)   集合與運算子   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==bFalse>>> a!=bTrue>>> a is bFalse>>> a is not bTrue>>> a==1 and b==3False>>> a==1 or b==3True>>> not b==3True>>> a==1 and not b==3True

python基礎資料型別 (Elementary Data Type)(四)-集合與運算子-python3筆記

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.