Python basic data type (iv)-collection and operator-python3 notes

Source: Internet
Author: User
Tags iterable

1. Collection

2. Dictionaries

3. Operator Precedence

1. Collection

Create: () set () Note: Create an empty collection with Set () Feature: element unique, unordered operation: & (Intersection)-(set)-(difference) method: S.add (x) #添加单个元素s. Update () #添加多个元素s. Remove () #移除元素s. Clear () #清空集合 # collection creation >>> SE = {<class} >>> print (Type (SE)) ' Set ' > >&    Gt;> se = {1,2,2,3} #去重, unique >>> print (SE) {1, 2, 3} >>> se = {1, ' a ', 2, ' B '} #无序      >>> SE {1, 2, ' A ', ' B '} #可hash的能放入集合 >>> hash ([up]) Traceback (most recent call last): File "<pyshell#24>", line 1, in <module> hash ([]) typeerror:unhashable type: ' List ' >>& Gt Hash ((a,2)) Traceback (most recent): File "<pyshell#25>", line 1, in <module> hash ((A , 2)) Nameerror:name ' A ' is not defined >>> hash (()) 1299869600 >>> hash (' qwe ')-91777        3703 >>> a Traceback (most recent): File ' <pyshell#28> ', line 1, in <module> A nameerror:Name ' A ' isn't defined >>> a= ' I love python ' >>> a ' I love Python ' >>> hash (a) -2061797837 >>> #定义空集合 (Factory mode definition collection) >>> SE = set () >>> print (Type (SE)) <class ' Set '    > #集合的运算 #属于 >>> a {1, 2, 3, 4, ' a '} >>> ' a ' in a True >>> ' B ' isn't in a True #延伸 >>> se={1,2,3,4} >>> se2={3,4,5,6} >>> se < se2 #包含 False > >> se <= se2 #包含 False >>> se! = se2 #不等于 True #并集 (two sets added and de-weighed) >>> se1={1,2,3 };se2={2,3,4} >>> se1|se2 {1, 2, 3, 4} #交集 (take two duplicate elements) >>> Se1&se2 {2, 3} #差集 (Previous set     Minus the repeating part of the collection Element) >>> Se1-se2 {1} >>> se2-se1 {4} #与非集 (take separate parts of the respective collection) >>> Se1^se2 {1, 4} #集合的基本方法 View collection methods: >>> 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 '] #添加单个元素 (add a single element) >>> se={1,2} >>> se.add (3) &GT;&GT;&G T Print (SE) {1, 2, 3} #添加多个元素 (add multiple elements (objects that can be iterated)) >>> se.update (' 4 ') >>> print (SE) {1, 2, 3, ' 4 '} >>> se.update (' 456 ') >>> print (SE) {1, 2, 3, ' 6 ', ' 4 ', ' 5 '} #移除元素 (specify remove) >>> s   E.remove (' 5 ') >>> print (SE) {1, 2, 3, ' 6 ', ' 4 '} #随机移除 >>> Se.pop () 1 #清空集合 >>> se.clear () >>> print (SE) Set ()

2. Dictionary

Note: Is the only mapping type created in Python: {key:value} #大括号创建字典的键时要加引号dict {key=value} #括号里赋值方式, name = object, do not quote the key and value in the dictionary are separated by ': ', a pair of keys and values form an item, a key and an item Use ', ' separates the characteristics: The key is unique, the repetition will be re-assigned the unordered key must follow the Python naming rules to add and value Cidt[key]=value #key存在则修改该值, did not add the property method:. Update ({}) #在字典中添加多个项. It       EMS () #返回字典的各个项. Keys () #返回字典的键. VALUES () #返回字典的值. Get (k) #如果键k在, returns the value of K, does not exist returns None.get (K,X) #如果键k在, returns the value of the key K, returns X.pop (k) #返回并移除键k所对应的元素, does not exist, throws an exception. Pop (k,x) #返回并移除键k所对应的元素, does not exist then returns x Summary: Key is unique, so it can be a number, a string , Ganso Summary: mutable object: List Set dict immutable object: str tuple# dictionary Unique mapping type, followed by hash, must be immutable object # definition Dictionary >>> 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 (t    Ype (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 ' > #字典取值 (using key values) >>> Di[1] 123 >> > di[2] 234 #字典修改 >>> di[1]= ' qwe ' >>> di {1: ' Qwe ', 2:234} #添加key: Value (key exists when the key is modified) Modify otherwise Add) >>> 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 (d i) {} #查看字典的属性方法 >>> 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 ', ' setd ' Efault ', ' Update ', ' values '] #fromkeys #用给定的键建立新的字典, each key defaults to none (mass production of new dictionaries) >>> Di.fromkeys ({' A ', ' B ', ' C '}) {' B ': None, ' C ': None, ' A ': none} #用给定的键建立新的字典, each key is Custom 123 >>> Di.fromkeys ({' A ', ' B ', ' C '},123) {' B ': 123, ' C ': 12 3, ' a ': 123}>>> Help (Di.fromkeys) Help on built-in function Fromkeys:fromkeys (iterable, Value=none,/) method of B Uiltins.type instance Returns a new dict with keys from iterable and values equal to value. #字典取值; value exists, then return value, no default return None, Also         Customizable >>> di {' W ': 123, ' E ': 456, ' R ': 789} >>> Di.get (' W ') 123 >>> di.get (' Q ') >>> di {' W ': 123, ' E ': 456, ' R ': 789} >>> di.get (' Q ', ' I don't exist ') ' I don't exist ' #items, display the dictionary as a tuple in the list Each >>> di.items (Dict_items (' W ', 123), (' E ', 456), (' R ', 789)]) >>> list (Di.items ()) #查 Look at every item in the dictionary [(' W ', 123),(' e ', 456), (' R ', 789)] #以列表的形式查看字典的所有键 >>> Di.keys () Dict_keys ([' W ', ' e ', ' R ']) #以列表的形式查看字典的所有值 >>& Gt Di.values () dict_values ([123, 456, 789]) #pop, specify the key and delete the corresponding value. If the key does not exist, you can customize the return value >>> Help (di.pop) to built-in function Pop:pop (...) method of Builtins.dict Instanc        E 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 ', ' I don't exist ') ' I don't exist ' #popitem, random Delete dictionary (no object required) >>> di {' R ': 789, ' W ': 123} >>> di {' R ': 789, ' W ': 123} >>> Di.popitem () (' W ', 123) >> > di {' R ': 789} #类似get, there is a return value, the update to the dictionary does not exist, the corresponding value defaults to none, can also be customized >>> di.setdefault (' R ') 789;>> Di.setdefault (' W ', 123) 123 >>> di {' R ': 789, ' W ': 123} >>> di.setdefault (' Q ') & gt;>> di {' R ': 789, ' W ': 123, ' Q ': none# Add and update a dictionary content to the original dictionary >>> 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. Operators

算数运算符: +,-,*,/,%,**,//    赋值运算符: = += -= *= /= %= **=    比较运算符: ==  !=  >  <  >=  <=    成员运算符: 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 basic data type (iv)-collections and operators-python3 notes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.