python simple data types

Preface

        Variables in python are equivalent to objects in C++, which contain various methods for programmers to use.

        There are also various built-in functions in python such as str(), sort() and other functions, which allow programmers to operate different objects.

        Python comments use "#"

        If python is not installed in windows, you can download and install it from the python official website.

        Generally, the python interpreter is automatically installed in Linux.

         You can write a python file, please note that it needs to end with .py (the actual Linux file attributes are not determined by the file suffix, but are determined when it is created and how it is created). Use the python interpreter to execute.

         You can also use the python terminal to write python code and execute it. Use exit() or Ctrl+d to exit the python terminal.

        Zen of Python:

1. Variables

       1.1 Variable naming

        Python variable naming is similar to variable naming in C language.

  • Can only contain letters, numbers, and underscores. Variable names can start with letters or underscores, but not numbers.
  • Variable names cannot contain spaces, and underscores can be used to separate words.
  • Don't use Python keywords and function names as variable names. i.e. don't use words that python reserves for special uses.

        2.1 Variable definition

        Python variable definition does not need to specify a type, just define it directly.

        2.2 Multi-variable assignment

a=b=c=1
a,b,c=1,2,'tom'

2. Type

        2.1 String

        2.1.1 Definition

        In Python, all strings are enclosed in quotation marks, and the quotation marks can be single quotation marks or double quotation marks. And supports escape symbols.

        This flexibility allows you to include double quotes and single quotes in strings.

    Strings in Python are immutable, which means that once a string is created, its characters cannot be modified directly. The contents can only be modified indirectly by creating a new string.

        2.1.2 Operation

  • Display each word with the first letter capitalized. title() method.

  •  Convert all to uppercase upper(), Convert all to lowercase lower()

  •  Concatenate strings, '+' or '+='

  •  Remove spaces. strip() deletes spaces at both ends, rstrip() deletes spaces on the right, and lstrip() deletes spaces on the left.

  • Split the string. Use the string split() method to split a string into a list of strings according to specified characters.

  • Concatenate strings. Use the join() function to join string lists according to specified characters. 

        2.1.3 String comparison

  • == and !=:

        == compares whether two string values ​​are the same, != is the opposite of ==. Both comparison methods are case-sensitive.

  •  >, <, >=和<=:

        String size comparison is based on the dictionary order of characters and is case-sensitive.

  • is:

        Used to compare whether two strings are exactly the same. Not just the value, but the address.

  • Case-sensitive comparison of strings 

       Convert all strings to be compared to uppercase or lowercase before comparing.

        Or use the str.casefold() method, which also converts uppercase characters to lowercase, but lower is only limited to characters that exist in ascll, and casefold is not limited to characters that exist in ascll.

        2.1.4 print statement in python2

        In python2 there is no need to put what you want to print in parentheses. Technically speaking, python3's print is not intentionally omitted, so the parentheses are essential. However, some python2 print statements also contain parentheses, and their behavior is slightly different from python3. 

         2.2 Integers

        2.2.1 Operation

        In python, you can add (+), subtract (-), multiply (*), divide (/), exponentiate (**), and take remainder (%) operations on integers.

         Use parentheses to modify the order of operations.

         2.2.2 Floating point numbers

        Python refers to large and small numbers as floating point numbers. Operations are also supported. However, the number of decimal places in the operation result is uncertain. This problem exists in all languages ​​​​when representing floating point numbers. The reason is due to the way the computer represents numbers internally.

        2.2.3 str() function

        The str() function can represent non-string values ​​as strings.

         2.3 List

        A list consists of a series of elements arranged in a specific order. It can contain strings, numbers, lists, etc. The list can contain any unrelated elements.

        Square brackets ([]) are used in python to represent lists. And use commas to separate elements:

        Using print to print a list will print all elements in the list, including square brackets.

         2.3.1 Accessing and using list elements

        Elements can be accessed using indexes. Like the C language, list indexes also start from 0. This is related to the underlying implementation of list operations.

Why does C language array index start from 0?

        Arrays in C language are represented by offsets of memory addresses. For example, arr[0] <=> arr + 0, arr is the starting address of the array, plus 0 is the first element. arr[1] <=> arr+1, the starting address is increased by 1, which is actually the starting address of arr plus the size of the element type, and the second element is accessed.

         A special syntax is also provided in python. By specifying an index of -1, you can return the last element of the list. This convention also applies to other negative indexes, for example: index -2 returns the second to last list element, and so on.

         Using list elements, you can also access them by index and assign and modify them.

         2.3.2 Adding elements to the list

  • To add an element to the end of a list , use the list's append method.

  • To add multiple elements to the end of the list , use the extend() method or use '+=' or '+'.

  •  To insert an element into a list, use insert() to add a new element anywhere in the list. You need to specify .

         2.3.3 Removing elements from a list

        If an element is deleted, it cannot be used.

  • To use del to delete elements, you need to know the position (index) of the element in the list.

For example, if you want to delete the "redline" element, its index is 2.

  •  Use the list method pop() to remove an element, and you can use a variable to get the element.

        When pop() does not pass parameters, it represents the last element, and the parameters passed represent the index of the corresponding deleted element.

  •  Remove elements based on value. Use the remove() method.

 Note: The method remove() only deletes the first specified value. If the value you want to delete may appear multiple times in the list, you need

Use a loop to determine if all such values ​​have been removed.

        2.3.4 Organization list

  • Permanently sort a list using the list's sort() method

         Passing the parameter reverse=True to the sort() method can achieve permanent sorting in alphabetical reverse alphabetical order.

         Since sorting requires comparison, the sort() method of a list requires the list elements to be the same.

        When an element of the list also contains multiple elements, you can customize a function to get the compared elements.

  •  Use the sorted() function to temporarily sort the list without modifying the original list.

  •  To reverse a list, use the reverse() method of the list.

  •  Get the list length. Use the len() function

  • Use a for loop to iterate through the entire list

         2.3.5 Create a list of values

  • Use the range() function to generate a range of numbers.

        The first parameter of range() is the minimum value of a series of numbers, the second parameter is the maximum value (exclusive), and the third parameter is the step size.

        The range() function can also set a third parameter to specify the step size. The default step size is 1.

 

  •  Use the range() function to create a list of numbers.

        Use the list() function, or use the list append() method.

  •  Perform simple statistical calculations on lists of numbers. Find the maximum, minimum and sum.

         2.3.6 List parsing

        List comprehensions combine the for loop and the code that creates new elements into one line and append the new elements automatically.

        To use this syntax, you first specify a descriptive list name and then define the expression in square brackets that generates the value you want to store in the list.

        The expression can be understood like this, element value + element set + condition

         There are other types of parsing in python:

  • If square brackets are used, it means list analysis
  • If curly braces are used, it indicates collection parsing
  • If curly braces are used and the elements inside are in key:value mode, it means dictionary parsing

        2.3.7 Copy list

        We can use slicing to copy the list. When the list does not contain variable-length elements, we can get a new list. If there is a variable-length type element, since the slice is copied during shallow copy, the element of the newly obtained list is copied from the reference of the element of the original list, and the two elements execute the same list.

         Without using slicing to copy the list, using direct assignment will not get a new list, but will get a reference to the list. The two lists actually share the same space.

        2.3.8 List functions and methods

  • function 
  1.  cmp(list1, list2): compare the elements of two lists
  2. len(list): Number of elements in the list
  3. max(list): Returns the maximum value of the list element
  4. min(list): Returns the minimum value of the list element
  5. list(seq): Convert tuples to lists
  • list method
  1. list.append(): Add a new object to the end of the list
  2. list.count(obj): Count the number of times an element appears in the list
  3. list.extend(seq): append multiple values ​​from another sequence at the end of the list at once
  4. list.index(obj): Find the index value of the first match of a value in the list
  5. list.pop(index=-1): Removes an element from the list, defaults to the last element, and returns the value of the element
  6. list.remove(obj): Remove the first occurrence of a value in the list
  7. list.reverse(): Reverse list elements
  8. list.sort(cmp=None, key=None, reverse=False): Sorting the original list will modify the original list
  9. list.sorted(cmp=None, key=None, reverse=False): Temporarily sort the list and return the sorted list without modifying the original list

        2.4 Tuple

        An object defined using elements enclosed in parentheses is called a tuple. You can access elements using indexes, but elements in a tuple cannot be modified.

        2.4.1 Modify tuples

         Although the elements in the tuple cannot be modified, the tuple variables can be modified.

        When a tuple contains variable-length elements, the variable-length elements can be modified:

        tuple join combination

        tuple copy

        2.4.2 Traversing tuples

        2.4.3 Delete tuples

        The elements in the tuple cannot be deleted, but we can use the del statement to delete the entire tuple

 

        2.4.4 Tuple comparison

        Tuples in python can be compared, and the comparison method is:

  1. If they are of the same type, compare the corresponding values ​​in sequence and return the result.
  2. If not of the same type, check if they are numbers
    1. If it is a number, perform the necessary numeric cast and then compare
    2. If one side is a number, then the element of the other side is "big" and the number is the smallest.
    3. Otherwise compare by alphabetical order of type names

If one element reaches the end first, the other longer tuple is larger

        2.4.5 Python built-in functions

  1. cmp(tup1,tup2): compares two tuple elements
  2. len(tup): Calculate the number of tuple elements
  3. max(tup): Returns the maximum value of the element in the tuple
  4. min(tup): Returns the minimum value of the element in the tuple
  5. tuple(seq): Convert list to tuple

        2.5 Dictionary

        In Python, a dictionary is a series of key-value pairs, each key is associated with a value, and you can access the value associated with it through the key. The type of the key can be a number, string, or tuple in python. It cannot be a list or dictionary. It is a comparable data type. The value associated with the key can be any data type such as a number, a string, a list, or even a dictionary. .

        Note: The keys of a dictionary in Python are immutable, and the values ​​are mutable.

        In Python, a dictionary is a series of key-value pairs enclosed in curly braces {}. Keys and values ​​are separated by colons, and key-value pairs are separated by commas.

         2.5.1 Accessing values ​​in a dictionary

        Values ​​in the dictionary can be accessed through key values ​​using square brackets. If you access a key value that is not in the dictionary, an error will be reported.

         2.5.2 Modify dictionary

         2.5.3 Traversing the dictionary

  • Traverse dictionary sequentially

  • Iterate through all keys and values ​​in the dictionary

         2.5.4 Dictionary built-in functions and methods

  • function
  1. cmp(dict1,dict2): compare two dictionary elements
  2. len(dict): Count the number of dictionary keys
  3. str(dict): output dictionary printable string representation

  4.  type(dict): Returns the type of input object
  • method
  1. dict.clear(): Delete all elements in the dictionary
  2. dict.copy(): Returns a shallow copy of the dictionary
  3. dict.fromkeys(seq,val): Create a new dictionary with the elements in the sequence seq as keys, and val is the initial value corresponding to all keys in the dictionary.

  4. dict.get(key, default=None): Returns the value of the specified key. If it does not exist, returns the default value.
  5. dict.has_key(key): Returns True if key is in the dictionary, otherwise returns false.
  6. dict.items(): Returns a traversable array of tuples as a list
  7. dict.keys(): Returns all the keys of a dictionary as a list
  8. dict.values(): Returns all values ​​in the dictionary as a list
  9. dict.setdefault(key, default=None): Similar to get(), but if the key does not exist in the dictionary, the key will be added and the value will be set to default
  10. dict.update(dict2): Update the key/value pairs of dictionary dict2 into dict
  11. dict.pop(key, default): Delete the value corresponding to the given key key in the dictionary, and the return value is the deleted value. The key value must be given. Otherwise, return the default value.

  12.  popitem(): Returns and deletes the last pair of keys and values ​​in the dictionary. The return element type is a tuple.

        2.6 Set

        A set is an unordered set of non-repeating elements. Its basic functions include relationship testing and elimination of duplicate elements. Set objects also support mathematical operations such as union, intersection, difference symmetric difference set, etc.

        2.6.1 Create a collection

        The elements in the collection are also enclosed by "{}", but to create an empty collection you need to use set(), and using {} will create an empty dictionary.

        The parameters required by the set collection class must be iterator types, such as sequences, dictionaries, etc. Then convert it into unordered and non-repeating elements. Since sets are non-duplicate, deduplication operations can be performed on strings, lists, and tuples.

  • Create empty collection
#创建空集合
s=set()
#创建列表类型集合
s1=set([])
#创建元组类型集合
s2=set(())
#创建字典类型集合
s3=set({})
  • Create a non-empty collection

         2.6.2 Collection operations

  • Add element

There are two ways to add elements, namely add() and update().

add(): The method is to add the incoming elements to the list as a whole:

update(): Split the incoming elements into single characters, save them in the collection, and remove duplicate elements. Multiple values ​​can be added at once

  • Delete element
remove(element) element: represents the element to be found and deleted Search the element element in the setVar set, and delete it if it exists; if it is not found, an error will be reported.
discard(element) element: represents the element to be found and deleted Find the element element in the setVar collection and delete it if it exists; if it is not found, do nothing.
pop() Removes and returns an undefined element in s of type set, raising a KeyError if it is empty.
clear() Clear all elements in the s collection

remove():

 discard():

 pop() and clear()

         2.6.3 Traversing the collection

        Note: Collections are not accessible via indexes. The index using the enumerate() function is established by the enumerate() function itself.

        2.6.4 Cross-complement of sets

        Since it is a collection, it will follow some of the operations of collections. Such as finding intersection, union and difference, etc.

intersection & Get common elements between two sets >>> set1 & set2
Union | Get all elements of two sets >>> set1
difference set - Get elements from one set that are not found in another set >>> set1 - set2
{1,2}
>>> set2 - set1
Symmetric difference set ^ Get the elements in sets A and B that do not belong to A&B >>> set1 ^ set2
  • intersection

        The symbol used to find the intersection of sets in python is '&', which returns the common elements of the two sets.

  •  Union

        The symbol used to find the union of sets in python is '|', which returns the elements after merging the two sets and removing duplicates.

  •  difference set

        The symbol used to find the difference set of sets in python is '-', which takes the elements in one set that are not in the other set.

        The difference symbol '-' is equivalent to the set method difference.

  •  Symmetric difference set

        The symbol used to find the union of sets in python is '^', which takes the elements of the two sets that do not exist in the intersection of the two sets.

        The symmetric difference set notation '^' is equivalent to the set method symmetric_difference

         2.6.5 Range judgment of collections

        Sets can use >, <, >=, <=, ==, != to determine whether a set is completely contained in another set. You can also use the child-parent set judgment function.

        These symbols are not used to compare the size of set elements, but to determine the relationship between two sets.

         2.6.6 Immutable collection frozenset

        Frozenset is an immutable collection. Unlike set, which can add and delete elements in the collection, the contents of this collection are immutable. Similar to strings and tuples. Other functions are the same as set.

        There are no set operation functions at all in the frozenset immutable collection, such as add()update() and remove(), discard() and pop()clear() methods.

 

 

Guess you like

Origin blog.csdn.net/weixin_57023347/article/details/131373813