python data type

As an object-oriented programming language, all data types provided by python are objects. For objects in python, that is, they can be understood as reference types provided in Java. Unlike Java, python is not compatible with the basic data types in cpp. The data declaration in python does not need to be displayed like cpp or Java. It is similar to auto automatic type judgment in cpp. The type of variables declared in python is determined by their assignment. At the same time, python is a language of if type, that is, variables can be changed to other data types by assignment in subsequent operations after initialization with one data type, that is, the data type of variables in python is variable.

int - integer

  1. Integer, different from cpp or java, the integer provided in python is also an object. Integer in python automatically supports large number operation without considering overflow.
  2. example
    a = 10 #Automatically recognized as integer int
    b = 100
    c = a + b
    # The integer of [- 5256] is placed in the data pool. For variables assigned the same value in this range, they actually point to the same data storage space
    m = 25
    n = 25
    print(id(m)==id(n)) # true will be returned, and the id is used to get the storage address of the variable
    m = 1000
    n = 1000
    print(id(m)==id(n)) # false will be returned
    d = int(5) # int is used to cast a parameter type to an integer
    e = int(input()) # Used to convert a string entered from the keyboard to an integer
    

float - floating point

  1. Floating point type, such as cpp or double (double precision floating point type) in Java is not provided in python.
  2. example
    a = 3.14 # Infer automatic type to float
    b = float(4.48) # Float is used to cast the parameter type to float
    c = float(input()) # Converts a string from standard input to a forced data type to float
    f = a + b
    d = float("inf") # Assign to infinity
    e = float("-inf") 3 Assign to infinitesimal
    

str - string

  1. character string.
  2. example
    s = "this is a piece of string." # The contents of double quotes are automatically inferred as strings
    ss = 'this is a piece of string, too.' # The contents of single quotation marks are automatically inferred as strings
    sss = """this
    is 
    multiple
    strings.""" # The contents in the three quotation marks are strings that span multiple lines
    s2 = str("this is string.") # str is used to cast a parameter to a string
    s3 = input() # Data obtained from standard input defaults to a string
    

bool - Boolean

  1. Boolean type.
  2. example
    a = True # The word True is reserved as the bool True value in python
    b = False  #The word False is reserved as a False value in python
    c = bool(1) # Nonzero elements are cast to True by bool 
    d = bool(0) # A zero value is cast to False by bool
    e = bool(100) # True
    f = bool(2+3) # After calculating the value of the expression, it is converted to True or False according to the above rules according to whether it is zero or not
    

list - list

  1. List, one of the most commonly used data types in python.
  2. example
    # 1. Declaration
    #The elements in brackets are inferred as lists
    lis = [1,2,3,4,5]
    #The element types in the list can be different
    lis = [1, 2.34, "string", [12,2]]
    # Declare an empty list
    lis = []
    # The list is generated by string method. The default separator is space. You can specify the separator
    lis = "this,is,a,string.".split(',')
    lis = "male: this is:dialog.".split(':', 1) # The second parameter specifies the maximum number of divisions
    # Declare the list through the list factory function
    lis = list("this is string.") # String as a list, split into a single list
    lis = list(range(1,10)) # range generates an iterative arithmetic sequence
    
    # 2. Use
    lis = [1,2,3,4,5]
    # Append element
    lis.append(1)
    # Index element
    lis[0] # Get the first element
    lis[-1] # Gets the first element from the back to the front
    # Remove element by value
    lis.remove(1) # Remove element 1 from the list
    # Remove elements by index
    def lis[2] # Remove the third element
    # Get the number of list elements
    size = len(lis)
    # Slice to get a fragment in the list
    lis[2:3] # Gets the from the second element to the fourth element
    lis[:] # Gets a copy of the entire list
    lis[:5] # Gets from the first element to the sixth element
    lis[4:] # Gets the from the fifth element to the last element
    lis[1:5:2] # Gets the from the first element to the fifth element in steps of two
    lis[::-1] # Get the copy from the whole list in steps of - 1, that is, get the reverse order of the list
    # Remove some list elements
    lis[1:3] = [] # Remove from the second element to the fourth element
    del lis[1:3] # ditto
    # Insert element
    lis.insert(0,4) # Insert element 4 at the first element position
    # List splicing
    lis.extend([1,2]) #Append and merge the list with [1,2]
    lis + [1,2,3] # Merge the list with [1,2,3]
    

Tuple - tuple

  1. Tuples, understood as restricted lists.
  2. example
    # statement
    tp = 1,2,3 # Comma separated automatic type inference to tuples
    tp1 = (1,2,3) # Usually use () to include tuples. Note that parentheses are not the flag of tuples
    tp2 = tuple((1,2,3)) # Tuple factory function converts iteratable parameters into tuples. Note that tuple requires only one parameter, so inner parentheses cannot be omitted
    tp3 = tuple() # Declare empty tuples
    
    # use
    tp = 1,1,2,3
    tp.count(1) # Gets the number of elements in the tuple
    tp.index(2) # Gets the current index of the parameter in the tuple
    

Set - variable set

  1. Variable set is characterized by that the elements in the set are not repeated, and the elements are automatically ordered. Subscript indexes can not be used to access the set elements.
  2. example
    # statement
    st = {1,2,3,1} # Comma separated single element data in braces is inferred as a collection by type, and duplicate elements will be ignored
    st1 = set([1,2,3,4,3,2]) # set converts the iteratable object parameter to a collection
    st2 = set() # Declare an empty collection. Directly use empty braces to declare it as an empty dictionary instead of a collection
    
    # use
    st = {1,2,3,3}
    st.copy() # Gets a copy of the collection
    st.clear() # Empty collection
    st.add(5) # Add elements to the collection
    st.pop() # Pop up the first element
    st.remove(5) # Delete element
    # Set specific operations are not given here
    

dict - Dictionary

  1. Dictionary is similar to HashMap in Java, that is, mapping or key value pairs.
    # statement
    dc = {'first':'a','second':'b','third':'c'} # Data types of key value pairs separated by commas in braces are inferred as dictionaries
    dc2 = dict(((1,'a'),(2,'b'))) # Use dict to declare the dictionary, where the parameter is a tuple, and the tuple element is also a binary corresponding tuple, in which the first value will be used as a key and the second value will be used as a value
    dc5 = dict(first=1,second=2) # The list is constructed by keyword parameter passing. The parameter name is used as the key and the parameter value is used as the value. Note that the parameter name cannot use quotation marks
    keys = [1,2,3,4,5] # The corresponding dictionary is obtained through the key list and value list
    values = ['a','b','c','d','e']
    dc3 = dict(zip(keys,values)) # zip encapsulates two equal length lists L1 and L2 into iterative objects in the form of ((l1[0],l2[0]),(l1[1],l2[1])...)
    dc4 = dict.fromkeys([1,2,3,4]) # Use dict.fromkeys to construct a dictionary for specifying keys and default values. The default values can be specified uniformly. The default value is None
    
    # use
    dc = {'first':'a','second':'b','third':'c'}
    dc['first'] # Dictionaries can index values by keys, but subscripts, such as dc[1], cannot be used
    dc.get('first', "not found") # . get obtains the value through the key, which is different from the previous method. When the given key does not exist, the previous method will throw an exception. Get will return the specified second parameter, which is None by default
    dc['first'] = 'aaa' # Reassign by key
    dc['other'] = '...' # Assigning a value to a key that does not exist will perform the operation of adding a new key value pair
    dc.update(first='aba') # Update the element. If the key exists, it will be updated. If the key does not exist, it will be added
    dc.copy() # Get a copy of the dictionary
    dc.keys() # Gets all keys and returns an iteratable object
    dc.values() # Gets all values and returns an iteratable object
    dc.items() # Gets the iteratable object for all key value pairs
    
    for key in dc: # Iterate directly on the dictionary and all keys will be iterated
       print(key) # Output key
       print(dc[key]) # Value corresponding to output key
       
    for key, value in dc.items(): # Iterate directly on key value pairs
       print(key) # Output key
       print(value) # Output value
        
    # You can use frozenset to create immutable collections
    a = {1,2,3,4}
    b = frozenset(a)
    

None

Compared with nullptr in cpp and null in java, None provided in python indicates no value, or the object does not refer to any actual data space.

a = None

Deep and shallow copy problem

Similar to the reference type objects in java, the assignment between python objects will have the problem of deep and shallow copy.

# The same is true for all reference types. Here, take the list as an example
lis = [1,2,3]
lis2 = lis # At this time, lis2 and LIS are absolutely equal, that is, they point to the same data space, and changing any value will lead to the modification of the data itself
lis[0] = 100
print(lis2[0]) # Output 100
print(id(lis)==id(lis2)) # Returns True
lis3 = lis.copy() # At this time, the values of lis3 and LIS are equal. They point to different data spaces. Changes to one of them will not affect the other
print(id(lis)==id(lis3)) # False will be returned
lis4 = lis[:] # Full slice is equivalent to lis.copy()

Keywords: Python

Added by unlishema.wolf on Sat, 11 Sep 2021 03:32:11 +0300