Pinch python novice advanced Chapter 3

Posted by pvraja on Mon, 18 Oct 2021 23:24:42 +0200

This article introduces and details the definition and detailed usage of python lists, tuples, and dictionaries, absolute dry goods

list

Definition of list:

  • List yes   Python   Used in   Most frequent   In other languages, it is often called   array
  • List use   []   Definition, data   Use between  ,  separate
  • Items in the list   Can change
  • Tabular   Indexes   from   0   start
    • Indexes   Is the data in   list   Position number in, index   It can also be called   subscript

Note: when taking values from the list, if   If the index range is exceeded, the program will report an error

demonstration:

# Define a list alist. A list can consist of strings, integers or sub lists
>>> alist = [10, 20, 'tom','alice', [1,2]]
>>> len(alist)  # Using the function len(), you can see the length of the list, that is, how many elements are separated by commas
5
# The list is also the following marked elements. The default starting subscript is 0, and the first element in the list alist is 10
>>> alist[0]
10
>>> alist[-1]  # Take out the penultimate element in the list alist, which is the sub list [1,2]
[1, 2]
>>> alist[2:4]  # Take out the second to fourth elements in the list alist, and the elements with subscript 4 do not contain
['tom', 'alice']
>>> 'tom' in alist  # Is the string 'tom' within the list alist range
True
# Splicing and reassignment of lists
>>> alist  # View the values in list alist
>>> type(alist)  # View the data type of list alist, which is list type
<class 'list'>
>>> type(100)  # View the data type of 100, which is int type
<class 'int'>
>>> alist + 100  # When splicing lists, they must be of the same type [all list types] before splicing can be completed
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
>>> alist + [100]  # After splicing, only the spliced results will be output, and the composition of the list alist will not be changed
>>> alist[-1]  # View the value of the last element of the list alist
[1,2]
>>> alist[-1] = 100  # The value of the last element of the modify list alist is 100
>>> alist[-1]  # View the value of the last element of list alist and verify the result
100
>>> alist  # View all elements in list alist
List operation:


	• use in or not in Judge membership
	• use append Method to append an element to the list(Commonly used)
>>> 10 in alist	  # Judge whether 10 is within the list alist range, and it is true
True
>>> 'alice' not in alist  # Judge whether alice is not within the list list list, false
False
>>> 'tom' not in alist  # Judge whether the string tom is not within the list alist range and is false
False
# Alist. < tab > < tab > can display the methods that alist can use
>>> alist.append(200)  # Append an element 200 to the list alist
>>> alist

tuple

Definition of tuple:

  • Tuple s are similar to lists, except that tuples are   Element cannot be modified
    • tuple   Represents a sequence of multiple elements
    • tuple   stay   Python   During development, there are specific application scenarios
  • For storage   A string of information, data   Use between  ,  separate
  • Tuple   ()   definition
  • Tuple   Indexes   from   0   start
    • Indexes   Is the data in   tuple   Location number in
  • In tuple   Contains only one element   When needed   Add a comma after the element
  • It is similar to score ranking and cannot be modified

demonstration:

>>> atuple = (1,2,'tom','alice')  # Define a tuple atuple
>>> len(atuple)  # Use the function len() to calculate the length of tuples, that is, the number of elements
4
>>> atuple[2:]  # Take out the elements with subscript 2 and later in tuple atuple, and the initial subscript is also 0
>>> atuple + (100,200)  # Tuple splicing, tuple itself will not change
>>> 'tom' in atuple  # Whether the string tom is in the tuple atuple is true
# Tuples are static lists. Once defined, they cannot be modified, and the elements in tuples cannot be re assigned
>>> atuple[0] = 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Dictionaries

Definition of Dictionary:

The data type in python is dictonart

  • The dictionary is   In addition to the list   Python   in   Most flexible   Data type for
  • Dictionaries can also be used to   Store multiple data
    • Usually used for storage   Describe a   object   Information about
  • Difference between and list
    • list   yes   Orderly   Collection of objects
    • Dictionaries   yes   disorder   Collection of objects
  • Dictionary use   {}   definition
  • Dictionary use   Key value pair   Store data, use between key value pairs  ,  separate
    • key   key   It's an index
    • value   value   It's data
    • key   and   value   Use between  :  separate
    • The key must be unique
    • value   You can take any data type, but   key   Only use   String, number, or   tuple

demonstration:

>>> adict = {'zhang': 123, 'san': 246}  # Define a dictionary variable adict
>>> adict  # View all elements in dictionary adict
{'zhang': 123, 'san': 246}
# You can only judge whether the key is within the adict range of the dictionary, but not the value
>>> 'zhang' in adict  # Key zhang, within the scope of dictionary adict
True
>>> adict['san']  #Take out the page number corresponding to the key san, which is 246
246
>>> adict['san'] = 247  # If the key san already exists in the dictionary, modify the page number corresponding to san to 247
>>> adict['san']
22
>>> adict['zhao'] = 400		# If the key zhao does not exist in the dictionary, it means that it is added in the dictionary
>>> adict							#View all elements in adict dictionary and add the key email
{'zhang': 123, 'san': 247, 'zhao': 400}
# The dictionary uses the key to get the corresponding value. You can't use the subscript to get the value, because the dictionary has no order
>>> adict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 0

Data type comparison

Classification by storage model:

  • Scalar type: numeric, string
  • Container type: list, tuple, dictionary

Classification by update model:

  • Variable type: list, dictionary
  • Immutable types: number, string, tuple
Demo 1
# Data storage mode: demonstration 1
>>> py_str = 'python'  # Define variable py_str, value 'python'
>>> py_str[0]  # You can view the variable py_ Character with STR subscript 0
'p'
>>> py_str[0] = 'P'  # Modify variable PY_ Characters with STR subscript 0 are not supported and cannot be modified
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> py_str = 'Python'  # Give variable PY_ When STR is assigned as a whole, the assignment is successful,

Summary:

  • When defining a variable, the system will open up a fixed length space in memory to store the value 'python' and 'py' of the variable_ STR is the mapping of this space, which is a whole and cannot modify a single character in a variable;

  • Re variable PY_ When STR is assigned, the system will reopen a fixed length space in memory to store the new value 'Python', and the system will py_str mapping points to the new space instead of modifying the original one;
Demo 2
>>> alist = [100,20,30]		# Define list alist with the value of [100,20,30]
>>> blist = alist			# Assign list alist to blist
>>> blist					# View all elements in list blist
>>> blist.append(200)		# Append an element to the list blist
>>> blist					# View all elements in list blist
[100, 20, 30, 200]
# Check all the elements in the list of alist, and find that there is no value assigned to alist, and the value of alist also changes, as shown in the following figure:
>>> alist
[100, 20, 30, 200]

Summary:

  • When we execute blist = alist, we actually make alist and blist point to a data storage space at the same time;
  • When blist is modified, the data storage space is modified, and alist also points to the same data storage space, and the values of all alists are changed;
# Verify that alist and blist point to the same storage space through id()
>>> id(alist)
140320705670024
>>> id(blist)
140320705670024
 Demo 3
# Create list clist. When modifying list clist, the value of list alist will not change 
>>> clist = alist[:]  # Redefine a list and assign the value of alist to clist by slicing
>>> id(clist)  # Check the id values of clist and alist. They are different. They point to different storage spaces
140320705692680
>>> id(alist)
140320705670024
>>> clist.append(50)  # Append an element to the list clist
# The values of list clist and list alist are different. The principle is shown in the following figure:
>>> clist
[100, 20, 30, 200, 50]
>>> alist
[100, 20, 30, 200]

Summary:

  • When we execute clist = alist [:], we actually reopen a new data storage space to store the data in alist, and then let clist point to the new storage space;
  • Therefore, the modification of list clist will not affect the values in list alist;

Classification by access model:

  • Direct access: Digital
  • Sequential access: string, list, tuple
  • Mapping access: dictionaries

Topics: Python list