Encapsulation and deconstruction

  • Encapsulate: = encapsulates an ancestor when comma-separated values appear to the right
t=1.2 Output (# 1, 2)
Copy the code
  • Destruct: = If the iterable is on the right and there are multiple identifiers on the left, the iterable value is assigned to the variable one by one
a,b=(1.2) # a=1 ,b=2
Copy the code
  • When deconstructing, the number of left and right sides should be equal
A, b = "123" # errors, because a = 1, b = 2, and "3" is not assigned to identifier. A, b, c = (1, 2, 3)Copy the code

Residual variable deconstruction

a,*rest,c="12345" # a="1",c="5", and the rest variable will encapsulate "234" into a list, which does not have to be called REST, but can be any identifier
a,b,*reset,c="12345" # a="1",b="2",c="5",rest="34"
a,*r1,*r2,b="12345" There can only be one residual variable destruct
_, *b, _ = [1.2.3] 
Copy the code

Residual variables encapsulate undeconstructed values into a list

Set the set

A collection of arbitrary data types is an unordered, non-repeatable, mutable collection of elements

Initialize the

  • Set () : empty set

  • set(iterable)

a = set(a)print(a)
b = set("123456")
print(b)
c = {"123"."abc"}
print(c)
d = set(range(5))
print(d)
Copy the code

The data in a set must be hash, which can be interpreted as immutable. Sets, bytearray, and set are mutable types and therefore cannot be put into sets

increase

  • Add (): If it exists, it is not added

  • Update (*othoners): Othoners must be iterable objects

a={1.2}
a.update([1.2.3, ("a"."b")])
print(a)
Copy the code

delete

  • Remove (item): deletes from the set. If not, KeyError is reported

  • Discard (item): Deletes from a set, if nothing is done

  • Pop (): Delete any element, set empty set KeyError

  • Clear (): Deletes all elements

a={1.2}
a.update([1.2.3, ("a"."b")])
print(a)
print(a.pop())
print(a.pop())
print(a.pop())
print(a.pop())
print(a.pop())
Copy the code

Modify the

  • It can only be deleted and added again

traverse

a={1.3.4.5.6}

for i in a:
    print(i)
Copy the code

The type that can be added to a set

  • Numeric types: int, float, complex

  • Boolean: True, False

  • The value can be string, bytes

  • tuple

  • None

The type that cannot be added to set

  • list

  • bytearray

Collective concept

  • Complete set: Set of all elements

  • Subsets and supersets: Set A in set B, A is A subset of B, and B is A superset of A

  • Proper subsets and proper supersets: A is A subset of B and A! Is equal to B, which means that A falls completely into B

  • Union: The result of combining sets

  • Intersection: The common part of a set

  • Difference set: Remove the sum of common parts

And set

  • The union (* others) : return more than one set of combined set, equivalent to the |
  • Others update (*) : equivalent to | =
A ={1,2,3} b={2,3,4} c= a.nion (b) # union()Copy the code

intersection

  • Intersection (*others): Grade at &
  • Intersection_update (*others): equals to &=
a={1.2.3}
b={2.3.4}
c=a.intersection(b) # return a new set
print(c)
a.intersection_update(b) Change the value of a set
print(a)
Copy the code

Difference set

  • Difference (*others): Equivalent to –
  • Difference_update (* OTHERS): Equivalent to -=
a={1.2.3}
b={2.3.4}
c=a.difference(b)
print(c)
a.difference_update(b)
print(a)
Copy the code

Symmetric difference set

  • symmetric_differece(*others)

  • symmetric_differece_update(*others)

a={1.2.3}
b={2.3.4}
c=a.symmetric_difference(b)
print(c)
a.symmetric_difference_update(b)
print(a)
Copy the code

Other operations

  • Issubset (* Others): Determines whether the current set is a subset of another set

  • Issuperset (* Others): Checks whether the current set is another set superset

  • Isdisjoint (* Others): Determines whether the current set has an intersection with another set

The dictionary

A dictionary is a collection of key-value pairs, and each KV pair becomes an entry or item. It is unordered, unrepeatable, and mutable

Initialize the

  • Dict (**kwargs): initializes with k-v pairs
  • Dict (iterable,**kwargs): Iterable is made up of binary groups
  • Dict (dict,**kwargs): Copies from other dict
  • dict.fromkeys(iterable)
a1=dict()
a2={}
a3=dict("a"=1,"b"=2)
a4=dict(a3,"c"=3,"d"=4)
a5=dict([("a",1),("b",2),("c",3)])
a=dict.fromkeys(range(5))
print(a)
b=dict.fromkeys(range(5),0)
print(b)
Copy the code

Element access

  • D [key]: returns value. KeyError is not reported

  • Get (key,default): returns default if no, and None if no default is set

  • Setdefault (key,default): set k-v yes, setdefault, value is None

a={"a":1."b":2}
print(a.get("c"))
print(a.get("c"."c"))
print(a.setdefault("C"."cc"))
print(a)
Copy the code

New and Modified

  • d[key]=value

  • Update (other): use the kv pair of another dictionary to update this dictionary, if key does not exist, add key, overwrite the value of the existing key

a={"a":1."b":2}
b={"b":3."c":4."d":5}
a["c"] =3
print(a)
a.update(b)
print(a)
Copy the code

delete

  • Pop (key,default): Default is not set. If the key does not exist, a KeyError is raised

  • Popitem (): Deletes items randomly. An error is reported if the dict is empty

  • Clear (): Clears the dictionary

traverse

  • d.keys()

  • d.values()

  • d.items()

a={"a":1,"b":2,"c":3}

for i in a.keys():
    print(i)

for i in a.values():
    print(i)

for i in a.items():
    print(i)

Copy the code

Traverse the delete

D = dict(a=1, b=2, c=3) for k,v in d.tems (): print(d.pop(k))Copy the code
D = dict(a=1, b=2, c=3) keys = [] for k,v in D. tems(): keys.append(k) for k in keys: d.pop(k)Copy the code

Dictionary keys, which can be understood as sets, require hash objects, that is, immutable values

Parses and generator expressions

List parsing

  • Return value for element in iterable if condition
  • Use brackets [], inside for loop, if conditional statement optional
  • Returns a new list
a = [x for x in range(5)] print(a) b = [(x,y) for x in range(5) if x > 3 for y in "abcd" if y > "b"] print(b) [(i,j) for I in range(7) if I >4 for j in range(20,25) if j>23] # theoretically faster # equivalent to for I in range(7) if I >4: For j in range(20,25): if j > 23: Pass [(I,j) for I in range(7) for j in range(20,25) if I >4 if j>23] # equivalent for I in range(7): for j in range(20,25): If I >4: if j>23: pass [(I,j) for I in range(7) for j in range(20,25) if I >4 and j>23] for I in range(7): For j in range(20,25): if I >4 and j>23: passCopy the code
  • Similarly, replacing [] with {} produces sets
a={x for x in range(5)}
# dictionary generator
{x:(x,x+1) for x in range(10)}
{x:[x,x+1] for x in range(10)}
{(x,):[x,x+1] for x in range(10)}
{[x]:[x,x+1] for x in range(10)} # error because the list is not hashable
Copy the code

The generator

  • (Return value for element in iterable if condition)
  • Generator expressions are evaluated on demand (or lazy evaluation, deferred evaluation), evaluating values only when needed
  • The generator can be iterated with for, but only once, or it can be evaluated by calling the next() method without raising a StopIteration error
a=(x for x in range(10)) for i in a: print(i) for i in a: Print (I) b = (y for y in range(3)) print(next(b)) print(next(b)) print(next(b)) print(next(b)) print(next(b)) print(next(b)) print(next(b) To quote StopIteration errorCopy the code