Python basics-variable summary, set()

table of Contents

1. Variable summary

1.1 Variable definition

1.2 id()

set

Immutable object


1. Variable summary

1.1 Variable definition

In Python, "variable" is more accurately called "name", and the assignment operation = is to bind a name to an object. It's like adding a label to the object.

Assigning variable a to another variable b is equivalent to attaching two labels a and b to object 2. Object 2 can be operated on through these two variables.

For details about the depth copy, see https://blog.csdn.net/zangba9624/article/details/86584513

The variable itself has no type information, the type information is stored in the object, which is very different from the variable in C/C++ (a variable in C is a memory area) 

1.2 id()

 The return value of the id method is the memory address of the object. Python will allocate memory for each object that appears.

1.3 Variable scope

  • L (Local) local scope
  • E (Enclosing) in the function outside the closure function
  • G (Global) global scope
  • B (Built-in) built-in scope

 Use   the rule of L --> E --> G -->B to search, that is: if you can't find it locally, you will find it locally (such as a closure), and if you can't find it, you will find it globally. Then go to the built-in to find.

Code specification: All uppercase letters of global variables, lowercase names of local variables.

1.3.1 If there is no global keyword inside the function

global is used to declare global variables

Read local variables first. If there are no local variables, read global variables. At this time, global variables cannot be assigned.

But for variable objects, you can operate on internal elements (such as append() pop()), and these operations will change global variables .

1.3.2 There is the global keyword inside the function

If there is a global keyword in the function, the variable is essentially a global variable, which can be read and assigned .

1.3.3 nonlocal keywords

Nonlocal is suitable for internal functions in nested functions to modify the value of external variables, and is used to declare external local variables

If you do not use the above keywords to modify global variables or external variables, python will hide the global variables by default

def scope_test():
    def do_local(): 
        spam = "local spam"  
    def do_nonlocal(): 
        nonlocal spam 
        spam = "nonlocal spam"   
    def do_global(): 
        global spam 
        spam = "global spam"       
    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()  
    print("After global assignment:", spam)       
scope_test()
print("In global scope:", spam)

输出结果
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

1.3.4 Closure

Definition of closure: If in an internal function, a reference is made to a variable in the external function (but not in the global scope ), then the internal function is considered a closure (closure)

set

Set is similar to dict. It is also a set of keys, but does not store value . Since the key cannot be repeated, there is no duplicate key in the set .

To create a set, you need to provide a list as an input set:

>>> s = set([1, 2, 3])
>>> s
{1, 2, 3}

Repeated elements are automatically filtered in the set and are not necessarily ordered

 

Frozenset()   cannot be appended, cannot be modified, and cannot be deleted.

s.add(key)The method can add elements to the set, and can be added repeatedly, but it will not have an effect

s.remove(key)The method can delete the specified element, if the specified parameter does not exist in the original collection, an error will be reported

The s.discard( key)   method can delete the specified element. The specified parameter is not in the original collection, but no error will be reported here.

s.clear() clears the collection. The result of emptying the dictionary is (), and the result of emptying the collection is set()

s.copy()  

s.pop()  randomly delete

s1.intersection(s2)  intersection s1&s2

s1.union(s2)     union s1|s2

s1.difference(s2)  差集 s1-s2

s1.symmetric_difference(s2)  cross complement s1^s2

s1.isdisjoint(s2) If the  intersection of  two sets is an empty set , then it returns True, if it is not an empty set , it returns False.

s1.issubset(s2)     determines whether s1 is a subset of s2

s1.issuperset(s2)   determines whether s1 contains s2, superset: superset, superset

Subsequent operations will modify s1

s1.difference_update(s2)       update s1 to the difference of s1 and s2

s1.intersection_update(s2)     s1 = s1 & s2

s1.symmetric_difference_update(s2)    s1 = s1 ^ s2

s1.update(s2)     adds the result of set s2 to set s1,

     The difference with s1.union(s2) is that s1 is modified 

    add() can only add a single value, update() can pass an iterable object and update multiple values

Two sets can do operations such as intersection and union in the mathematical sense

Intersection:

li1 = ["nicholas","pony","robin","jack"]
li2 = ["nicholas","charles","Richard "]
s1 = set(li1)
s2 = set(li2)
v = s1.intersection(s2)
#这里也可以这样写
#v = s1&s2
并集
v = s1.union(s2)
差集
v = s1.difference(s2)
或者
v=s1 - s2
>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>> s1 | s2
{1, 2, 3, 4}

Cross complement

li1 = ["nicholas","pony","robin","jack"]
li2 = ["nicholas","charles","Richard ","jack"]
s1 = set(li1)
s2 = set(li2)
v = s1.symmetric_difference(s2)
print(v)
print(s1 ^ s2)
输出
{'robin', 'Richard ', 'charles', 'pony'}
{'robin', 'Richard ', 'charles', 'pony'}

The principle of set is the same as that of dict. Therefore, variable objects cannot be placed in the same way . Because it is impossible to judge whether two variable objects are equal , there is no guarantee that there will be no duplicate elements in the set.

Immutable object

str is an immutable object, and list is a mutable object

As we mentioned above, str is an immutable object, and list is a mutable object.

For mutable objects , such as list, operate on the list, and the contents of the list will change, such as:

>>> a = ['c', 'b', 'a']
>>> a.sort()
>>> a
['a', 'b', 'c']

For immutable objects , such as str, operate on str:

>>> a = 'abc'
>>> a.replace('a', 'A')
'Abc'
>>> a
'abc'

For an immutable object, calling any method of the object itself will not change the content of the object itself. On the contrary, these methods will create a new object and return, in this way, it is guaranteed that the immutable object itself is always immutable

The elements of the collection must be immutable
examples

set1= {"hello",[1,2]}
print(set1)
输出
TypeError: unhashable type: 'list'

The output result reports an error, the list cannot be hashed, but the list can be used when creating a collection

Guess you like

Origin blog.csdn.net/zangba9624/article/details/106185822