I python recording learning process -Day06 is id == / block / set / copy shades

A, is == id usage

  In Python, id is the memory address, as long as you create a data (objects) then it will open up a space in memory, this data temporarily loaded into memory, this space has a unique identity, like identity card number, identifies the memory address space is called, that is, the data (object) id, then you can use the id () to get the memory address of the data:

name = 'Dylan'
print(id(name)) # 4319709032

== is the comparison value is equal on both sides, which in return is a result of True or False.

is relatively both sides of the memory address are equal, if memory addresses are equal, then the points on both sides of the same memory address. Which in return is a result of True or False.

name = ['Dylan']
name2 = ['Dylan']
print(name is name2)    # False
print(name == name2)    # True
print(id(name))         # 4387384328
print(id(name2))        # 4387382920

# 这里表示:name name2数值是一样的,但却不是同一个内存地址。

So: If memory addresses are the same, then the value is certainly the same, but if the values ​​are the same, not necessarily the same memory address.

Second, code block

  • Python program is configured by the code block, the block is a text python program, he is executed as a unit.

    Block: a module, a function, a class, a file, etc. is a block of code.

  • Each command is entered interactively as a code block.

    What is interaction?

    Python is let into the interpreter and in cmd, each line of code is a code block.

Third, the caching mechanism in the same block of code

  • Prerequisites: within the same block.
  • Mechanism content: the Python commands executed during the same block of code to initialize the object, checks whether the value already exists, if present, it will be reused. In other words: When you perform the same block, encountered command to initialize the object, he will be initialized with the value of this variable is stored in a dictionary, in the face of new variables will first query records in the dictionary, If you have the same record then it will re-use this value before this dictionary. So you example given, when the file executed (same block) will i1, i2 two variables point to the same object, then they meet the caching mechanism in the presence of only one memory, namely: the same id.
  • Suitable for: int (float), BOOL, str.
  • Specific rules:
    • int (float): any number in the same block of code are multiplexed.
    • bool: True and False 1,0 way will exist in the dictionary, and reuse.
    • str: Almost all of the strings will meet the caching mechanism.
  • Advantages: improve performance, save memory.

Caching mechanism in different code blocks (small data pool)

  • Prerequisites: the different code blocks.

  • Mechanism content: Python automatically integer from -5 to 256 were cached , when you these integer assigned to the variable, and will not re-create the object, but the use of already created the cache object.

    python string will be certain rules in the string resides pool , create a copy, when you these strings assigned to the variable, and will not re-create the object, but used in a string resides in the pool is created Object.

      In fact, both the cache or pool resides strings are made of a python optimization, is to string integer, and certain rules of ~ 5-256, put in a 'pool' (container, or dictionaries), whether the program variables that point to a string or integer within these ranges, then he quoted directly in the 'pool', the implication is to create a memory of.

  • Suitable for: int (float), BOOL, str.

  • Specific rules:

    • int (float): So we all know that for integers, the range of small data pool is -5 to 256, if multiple variables are pointing to the same (within this range) numbers, they are pointing in memory It is a memory address.
    • bool: True and False 1,0 way will exist in the dictionary, and reuse.
    • str: String satisfy the rule.
  • Advantages: improve performance, save memory.

  • to sum up:
    • Interview questions test.
    • Answer when we must make it clear: for a caching mechanism under the same code block. Another application of different caching the code block (small data pool)
    • Small data pool: numbers in the range of -5 to 256.
    • The advantages of caching mechanism: improve performance, save memory.

Fourth, the collection (understand)

Sets are unordered, unique data set that is inside the hash element (immutable type), but the hash itself is not set (it is set dictionary do not bond).

  • A collection of the most important points:
    • De-emphasis, the list becomes a collection, automatically go heavier.
    • Relationship test, before the intersection of two sets of test data, poor, union and other relations.
  • Collection and dictionary

    • Create a collection of

      # 方法一
      set1 = set({'name', 'Dyaln', 'age', 111, 434})
      # 方法二
      set1 = {'name', 'Dyaln', 'age', 111, 434}
    • Dictionary and a set of formats:

      # 字典
      dic = {'name':'Dylan', 'age': 18}
      # 集合
      set1 = {'name', 'age', 18, False, True, }
    • Empty dictionary:

      dic = {}
      # 或者
      {}
      print({}, type({}))     # {} <class 'dict'>
    • Empty set:

      set()
      print(set(), type(set()))       # set() <class 'set'>
    • The effectiveness of the collection:

      set1 = {[1, 3, 5], 3, {'name': 'Dylan'}}
      print(set1)     
      # 报错
        File "/Users/yaoyaoba/Full_stack_22/day06/练习.py", line 24, in <module>
      set() <class 'set'>
          set1 = {[1, 3, 5], 3, {'name': 'Dylan'}}
      TypeError: unhashable type: 'list'
      # 集合内的元素必须是 可合希类型(不可变数据类型)
  • Set of operations

    • increase

      • set.add()

        set1 = {'name', 'Dylan', 'xiaowang', 'yaoyao', 'age'}
        set1.add('xx')
        print(set1)     # {'xiaowang', 'xx', 'age', 'yaoyao', 'name', 'Dylan'}
      • set.update () iteration increases (automatically removes duplicate)

        set1 = {'name', 'Dylan', 'xiaowang', 'yaoyao', 'age'}
        set1.update('abcdedfdaefdafdsa')
        print(set1)     # {'yaoyao', 'age', 'd', 'e', 'a', 'Dylan', 'xiaowang', 'b', 'f', 'c', 'name', 's'}
    • delete

      • set.remove () to delete pressing element

        set1 = {'name', 'Dylan', 'xiaowang', 'yaoyao', 'age'}
        set1.remove('age')
        print(set1)     # {'xiaowang', 'yaoyao', 'Dylan', 'name'}
      • set.pop () randomly deleted

        set1 = {'name', 'Dylan', 'xiaowang', 'yaoyao', 'age'}
        set1.pop()
        print(set1)      # {'yaoyao', 'age', 'xiaowang', 'Dylan'}
      • set.clear () empty set

        set1 = {'name', 'Dylan', 'xiaowang', 'yaoyao', 'age'}
        set1.clear()
        print(set1)     # set()
      • del set Delete Collection

        set1 = {'name', 'Dylan', 'xiaowang', 'yaoyao', 'age'}
        del set1
        print(set1)     # 会报错,因为己经没有这个集合了
        # 报错信息如下:
        Traceback (most recent call last):
          File "/Users/yaoyaoba/Full_stack_22/day06/练习.py", line 28, in <module>
            print(set1)     # 会报错,因为己经没有这个集合了
        NameError: name 'set1' is not defined
    • Other sets of operations

      • Intersection. (Or & intersection)

        set1 = {1, 2, 3, 4, 5}
        set2 = {4, 5, 6, 7, 8}
        print(set1 & set2)  # {4, 5}
      • Union. (| Or union)

        set1 = {1, 2, 3, 4, 5}
        set2 = {4, 5, 6, 7, 8}
        print(set1 | set2)  # {1, 2, 3, 4, 5, 6, 7, 8} 
      • Difference sets. (- or difference)

        set1 = {1, 2, 3, 4, 5}
        set2 = {4, 5, 6, 7, 8}
        print(set1 - set2)  # {1, 2, 3} 
      • Anti intersection. (^ Or symmetric_difference)

        set1 = {1, 2, 3, 4, 5}
        set2 = {4, 5, 6, 7, 8}
        print(set1 ^ set2)  # {1, 2, 3, 6, 7, 8}
      • Subset and superset

        set1 = {1,2,3}
        set2 = {1,2,3,4,5,6}
        
        print(set1 < set2)
        print(set1.issubset(set2))  # 这两个相同,都是说明set1是set2子集。
        
        print(set2 > set1)
        print(set2.issuperset(set1))  # 这两个相同,都是说明set2是set1超集。
      • List deduplication

         l1 = [1,'Dylan', 1, 2, 2, 'Dylan',2, 6, 6, 3, 'Dylan', 4, 5]
        # set1 = set(l1)
        # l1 = list(set1)
        # print(l1)
        
        # 用处:数据之间的关系,列表去重。

Fifth, copy depth

copy is actually a copy, also known as a copy. In fact, the depth of copy is complete copy, and a copy of part of the meaning.

  • Look at the assignment operator

    l1 = [1, 2, 3, ['Dylan', 'age']]
    l2 = l1
    l1.append(456)
    print(l1)   # [1, 2, 3, ['Dylan', 'age'], 456]
    print(l2)   # [1, 2, 3, ['Dylan', 'age'], 456]
    print(id(l1))   # 4387382920 内存地址是一样的
    print(id(l2))   # 4387382920 内存地址是一样的

    For the assignment operator is, l1 and l2 points to the same memory address, so they are exactly the same, l1, l2 points to the same list, any changes in a variable on the list, after the rest of the variables list this list is the list after the change.

  • Shallow copy copy

    l1 = [1, 2, 3, ['Dylan', 'age']]
    l2 = l1.copy()
    print(id(l1))   # 4335892104
    print(id(l2))   # 4335903304
    # 这说明,通过 copy 出来的新列表,在内存中又开辟了一块新的内存空间,两者间不是指向的同一个列表。
    # 但是,如果再做如下操作你会发现什么?
    
    print(id(l1[-1]))   # 4370607112
    print(id(l2[-1]))   # 4370607112
    # 你会发现,咦?内存地址是一样的,说明是同一个数据。

    From this we can see that, in fact, a shallow copy just copies the shell of a list.

    For shallow copy, it just re-created in memory opens up a space for a new list, but the elements in the new list with elements of the original list is common.

    There is also a problem:

    When changing immutable data type list, the new contents of the list is not to be changed together, because it is a hash of data types, such as a list, data type of the variable to be modified or deletions to the column, then the new The list changes together.

  • Deep copy deepcopy

    import copy
    l1 = [1, 2, 3, ['Dylan', 'age']]
    l2 = copy.deepcopy(l1)
    print(id(l1))   # 4343088456
    print(id(l2))   # 4370618248
    # 这说明,通过 copy 出来的新列表,在内存中又开辟了一块新的内存空间,两者间不是指向的同一个列表。
    
    print(id(l1[-1]))   # 4379005512
    print(id(l2[-1]))   # 4379005832
    # 咦?内存地址不一样了,说明不是同一个数据了。
    
    print(id(l1[0]))    # 4305226112
    print(id(l2[0]))    # 4305226112
    # 哎我去!又一样了,咋回事儿?

    Deep copy feature is the variable's data type to re-create an in memory, rather than a variable data types are in use before.

    However, the same copy as shallow as immutable data types, even if the same memory address, when you change him, along with the new list will not be changed, only because he is immutable data types (hashable).

  • Related interview questions

    l1 = [1, 2, 3, [22, 33]]
    l2 = l1[:]
    l1[-1].append(666)
    print(l1)   # [1, 2, 3, [22, 33, 666]]
    print(l2)   # [1, 2, 3, [22, 33, 666]]
    浅copy: list dict: 嵌套的可变的数据类型是同一个。
    深copy: list dict: 嵌套的可变的数据类型不是同一个 。

Guess you like

Origin www.cnblogs.com/guanshou/p/12046854.html