Python_Process Control and Data Junction Structure

Posted by Devsense on Wed, 31 Jul 2019 10:43:49 +0200

Process Control - ---------------------------------------------------------------------------------------------------------------------------------------

Conditional Judgment

  • Grammar:

    # Single branch
    if <condition>: 
        <Execution code block>
    
    # Multi-branch
    if <condition1>: 
        <Execution block 1>
    elif <condition2>: 
        <Execution code block 2>
    elif <condition3>: 
        <Execution block 3>
    else:
        <Execution code block>
    
    
    # Note:
        # condition must be a bool type
        # if elif else statement is followed by a colon, the block of execution code after the colon needs to be indented by a new line 
  • Examples:

    # Single branch example
    age = 18
    if age < 20:
        print("tool small")
    
    # Multiple Branch Example (Grading)
    result = int(input('Please input your result: '))
    if result >= 90:
        print("Your result is A")
    elif 80 <= result < 90:
        print("Your result is B")
    elif 70 <= result < 80:
        print("Your result is C")
    elif 60 <= result < 70:
        print("Your result is D")
    else:
         print("Your result is E")
    
    #Note:
        # input() is a built-in function that interacts with the user in the console, obtains user input, and returns a string.
        # int(value) Converts a given value value value to an integer

loop

  • while loop

    # grammar
    while cond:
        block
    
    while True:   # Dead cycle
        pass
    
    # Example
    a = 10
    while a : # When a = 0, 0 is equivalent to False, but it does not enter the loop.
        print(a)
        a -=
  • for loop

    # grammar
    for element in interatable:   # Iterable objects have iteratable elements and enter a loop
        block
    
    # Example: Cyclic output of numbers less than 10
    for i in range(0, 10):
        print(i)
    
    # Note:
          # range(stop) counter
        # range(start, stop, step) generates a sequence that traverses the value between start and stop, and does not pack before and after the package; step represents the step size, default is 1;
  • continue skips the current loop and proceeds to the next one
  • break ends the current loop
  • Else clause: If the loop ends properly, the else clause will be executed

Data structure - ---------------------------------------------------------------------------------------------------------------------------------------

concept

  • Data structure is a collection of data elements organized together in some way, which can be numbers or characters; in Python. The most basic data structure is sequence. Each element in a sequence is assigned an ordinal number (that is, the location of the element, called an index, which starts at 0, that is, the first index is 0, the second one is 1, and so on).

list

  • List: An ordered collection that can be modified and represented by []

  • Definition list

    • Format: list_name = [1, 2, 3, 4, 5]

    • Empty list: list_name= []

    • List operation

      >>> lst = [1, 2, 3]
      
      # Appnd (obj), append element at the end, modify in place and return None, time complexity O(1)
      >>> lst.append(5)       
      >>> lst
      [1, 2, 3, 5]
      
      # list_name[index] = value index access modification, note that the index cannot be crossed
      >>> lst[3] = 4      
      >>> lst
      [1, 2, 3, 4]
      
      # insert(index, obj) inserts the element obj at the specified index position, modifies and returns None locally, with time complexity O(n), which can cross the bounds: over the upper bound, tail addition; over the lower bound, head addition.
      >>> lst.insert(1,6)     
      >>> lst
      [1, 6, 2, 3, 4]
      
      # extend(interatable), which appends iteratable elements to the list, modifies them locally and returns None
      >>> lst.extend(range(7,10))
      >>> lst
      [1, 6, 2, 3, 4, 7, 8, 9]
      >>> lst.extend([11, 12])
      >>> lst
      [1, 6, 2, 3, 4, 7, 8, 9, 11, 12]
      
      # + Connect the two lists to produce a new list, with the original list unchanged
      >>> lst + [100, 200, 300]
      [1, 6, 2, 3, 4, 7, 8, 9, 11, 12, 100, 200, 300]
      >>> lst     # The original list remains unchanged
      [1, 6, 2, 3, 4, 7, 8, 9, 11, 12]
      
      # * Repeat this list element n times to return to the new list; note the difference between the following examples
      >>> lst * 3
      [1, 6, 2, 3, 4, 7, 8, 9, 11, 12, 1, 6, 2, 3, 4, 7, 8, 9, 11, 12, 1, 6, 2, 3, 4, 7, 8, 9, 11, 12]
      >>> lst     # The original list remains unchanged
      [1, 6, 2, 3, 4, 7, 8, 9, 11, 12]
      >>> [1, 2, 3] * 3
      [1, 2, 3, 1, 2, 3, 1, 2, 3]
      >>> [[1, 2, 3] * 3]
      [[1, 2, 3, 1, 2, 3, 1, 2, 3]]
      >>> [[1, 2, 3] ] * 3
      [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
      
      # remove(value), matching the value of the first value from left to right, deleting if found, modifying in place and returning None
      >>> lst = [1, 2, 3, 1, 2, 5, 6]
      >>> lst.remove(1)
      >>> lst
      [2, 3, 1, 2, 5, 6]
      
      # pop(index), which does not specify index, deletes an element from the end of the list, and specifies index to delete an element from the index, returns the deleted element, and throws an error: IndexError
      >>> lst.pop()
      6
      >>> lst
      [2, 3, 1, 2, 5]
      >>> lst.pop(3)
      2
      >>> lst
      [2, 3, 1, 5]
      
      # clear(), clear all elements of the list, leaving an empty list
      >>> lst.clear()
      >>> lst
      []
      
      # reverse(), sorting elements in the list in descending order, modifying them locally and returning None
      >>> lst = [1, 2, 3, 1, 2, 5, 6]
      >>> lst.reverse()
      >>> lst
      [6, 5, 2, 1, 3, 2, 1]
      
      # sort(key=None, reverse=False), sort the elements in the list, modify them locally and return None; default is ascending, if reverse=True, descending; key is a function that specifies if sort
      >>> lst.sort()
      >>> lst
      [1, 1, 2, 2, 3, 5, 6]
      >>> lst.sort(reverse=True)
      >>> lst
      [6, 5, 3, 2, 2, 1, 1]
      
      # In includes relation judgment, that is, whether the element on the left side of in is included in the list on the right side; returns Boolean value
      >>> [1, 2] in [1, 2, [3, 4]]
      False
      >>> [3, 4] in [1, 2, [3, 4]]
      True
      
      # List replication: lst1 = lst2
      >>> a = list(range(4))  # Generate a new list a
      >>> b = list(range(4))  # Generate a new list b
      >>> a == b  # Determine whether the elements in list a and list b are the same
      True
      >>> c = a       # Point list c to the list memory address of list a, so when you modify list c or list a, you modify the list elements of the same memory address that a and c point to.
      >>> c[2] = 10
      >>> c
      [0, 1, 10, 3]
      >>> a
      [0, 1, 10, 3]
      >>> b       # Although lists a and b have the same contents, lists b and a point to different memory addresses, so when list a is modified, List b does not change.
      [0, 1, 2, 3]
      >>> id(a), id(c), id(b)     # Look at the memory address by id(), which is visible next time. a and c have the same memory address.
      (4509036368, 4509036368, 4509036288)
      
      # copy(), shadow copy (shallow copy), encounter reference type, copy only reference
      >>> a = [1, [2, 3], 4]  
      >>> b = a.copy()    # Element replication in the list, list referenced in the list, only copy the reference address, that is, list referenced in column a and b is the same memory address list.
      >>> b
      [1, [2, 3], 4]
      >>> b[1][1] = 11    # When b modifies the list elements referenced in the list, because the list referenced in the list of a and b points to the same memory address, a will also be modified accordingly.
      >>> b
      [1, [2, 11], 4]
      >>> a       
      [1, [2, 11], 4]
      >>> b[0] = 99       # Because the elements in the list are copied directly, when b modifies the elements, a does not change.
      >>> b
      [99, [2, 11], 4]
      >>> a       
      [1, [2, 11], 4]
      
      # Deep copy (call copy module; importcopy) directly copies all elements, and the reference type in the list directly copies the reference elements.
      >>> import copy
      >>> a = [1, [2, 3, 4], 5]
      >>> b = copy.deepcopy(a)
      >>> b
      [1, [2, 3, 4], 5]
      >>> b[1][1] = 88    # The list referenced in the list copies the contents of its list directly, so when List b changes, list a does not change.
      >>> b
      [1, [2, 88, 4], 5]
      >>> a
      [1, [2, 3, 4], 5]
      
      # random() random number
      >>> import random
      >>> random.random()
      0.8953651046887807
      >>> random.random()
      0.02852709684663768
      
      >>> random.randint(5, 20)       # Returns integers between 5 and 20
      6
      >>> random.randint(5, 20)
      15
      
      >>> random.randrange(11, 100, 2)    # Returns a random value of a 2-incremental integer between 11 and 100 with a default step size of 1
      57
      >>> random.randrange(11, 100, 2)
      41
      
      >>> random.choice(['scissors', 'stone', 'cloth'])    # Random selection of an element from a non-null sequence
      'scissors'
      >>> random.choice(['scissors', 'stone', 'cloth'])
      'stone'
      
      >>> random.sample('abcdefghijklmnopqrstuvwxyz!@#$%^&*()', 8)    # Extract n different elements from a non-empty sequence and generate a new list
      ['!', 'n', '&', 'd', 'q', 'l', 's', 't']
      >>> random.sample('abcdefghijklmnopqrstuvwxyz!@#$%^&*()', 8)
      ['x', '@', 'c', 'p', 'a', 'u', 'h', 'g']
      
      >>> lst = [1, 2, 3, 4, 5]
      >>> random.shuffle(lst)     # In-place scrambling list sorting
      >>> lst
      [2, 5, 3, 1, 4]
  • Index: The elements in the sequence are numbered, incremental from 0, index 0 points to the first element, and the last element can be represented by -1.

tuple

  • Tuple: not modifiable, represented by ()
  • Define tuples:
    • tuple_name = (1, 2, 3, 4)
    • An element tuple definition: (1) Note that there is a comma
    • Empty tuples: tuple_name = (), tuple_name = tuple() factory method
  • As with lists, they can be accessed through index

  • Tuple operation: Tuple is read-only, so add, delete and check operations are not available.

    >>> tup = tuple(range(1, 10, 2))  # interable
    >>> tup
    (1, 3, 5, 7, 9)
    
    >>> t = (1,)  # Note that an element needs a comma
    >>> t * 5     # Generate a new tuple with the original tuple unchanged
    (1, 1, 1, 1, 1)
    >>> t
    (1,)
    
    >>> tup[2]    # View the value of the tuple's specific index location through index
    5
    
    # count(value), the number of times the value in the tuple is returned
    >>> tup = (1, 2, 3, 2, 3, 2)
    >>> tup.count(2)  
    3
    
    # len(tuple) returns the number of elements in a tuple
    >>> len(tup)
    6

Dictionaries

Topics: PHP less Python