[Deep Learning] Python and NumPy Series Tutorials (3): Python Container: 1. Detailed explanation of List (initialization, indexing, slicing, updating, deletion, common functions, unpacking, traversal)

Table of contents

I. Introduction

2. Experimental environment

3. Python Containers (Containers)

0. Introduction to containers

1. List

1. Initialization

a. Create an empty list

b. Initialize the list with existing elements

c. Using list comprehension

d. Copy list

2. Indexing and slicing

a. Index

b. Negative index

c. to slice

3. Common operations (update, delete)

a. Update a single element

b. Update slice

c. Delete a single element

d. Delete the slice

e. Incremental update

f. Copy updates

4. Commonly used functions

append(element): Adds an element to the end of the list.

extend(iterable): Adds elements of an iterable object to the end of the list.

insert(index, element): Insert an element at the specified index position.

remove(element): Removes the first matching element from the list.

pop(index): Removes and returns the element at the specified index position.

index(element): Returns the index of the first occurrence of the specified element.

count(element): Returns the number of times the specified element appears in the list.

sort(): Sort the list in place, in ascending order.

reverse(): Reverse the list in place.

copy(): Returns a shallow copy of the list.

5. Unpacking

a. Basic unpacking

b. Extended unpacking

6. Traverse       

a. Use a for loop

b. Use while loops and indexes

c. Use the enumerate() function


I. Introduction

        Python is a high-level programming language created by Guido van Rossum in 1991. It is known for its concise, easy-to-read syntax, powerful functionality, and wide range of applications. Python has a rich standard library and third-party libraries that can be used to develop various types of applications, including web development, data analysis, artificial intelligence, scientific computing, automation scripts, etc.

        Python itself is a great general-purpose programming language and, with the help of some popular libraries (numpy, scipy, matplotlib), becomes a powerful environment for scientific computing. This series will introduce the Python programming language and methods of using Python for scientific computing, mainly including the following content:

  • Python: basic data types, containers (lists, tuples, sets, dictionaries), functions, classes
  • Numpy: arrays, array indexing, data types, array math, broadcasting
  • Matplotlib: plots, subplots, images
  • IPython: Creating notebooks, typical workflow

2. Experimental environment

        Python 3.7

        Run the following command to check the Python version

 python --version 

3. Python Containers (Containers)

0. Introduction to containers

        Containers in Python are objects used to store and organize data. Common containers include List, Tuple, Set and Dictionary.

  • Lists are ordered mutable containers that can contain elements of different types and are created using square brackets ([]).
my_list = [1, 2, 3, 'a', 'b', 'c']
  • Tuples are ordered immutable containers that can also contain elements of different types and are created using parentheses (()).
my_tuple = (1, 2, 3, 'a', 'b', 'c')
  • A set is an unordered and non-duplicate container used to store unique elements. It is created using curly brackets ({}) or the set() function.
my_set = {1, 2, 3, 'a', 'b', 'c'}
  •  A dictionary is an unordered container of key-value pairs used to store values ​​with unique keys. It is created using curly braces ({}) or the dict() function.
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}

        These containers provide different methods and operations for storing, accessing and processing data. You can choose a suitable container type according to your specific needs.

1. List

The most commonly used sequence type can be modified at will after creation, and various operations can be performed flexibly.

1. Initialization

a. Create an empty list

        To create an empty list, use empty square brackets [] or list()function initialization.

empty_list = []
empty_list = list()

b. Initialize the list with existing elements

        An initial element can be provided when creating the list. The initial element can be a constant, variable, or expression.

numbers = [1, 2, 3, 4, 5]
fruits = ['apple', 'banana', 'orange']

c. Using list comprehension

        List comprehensions are a quick way to create lists based on specific rules and expressions.

squares = [x**2 for x in range(1, 6)]  # 生成包含1到5的平方的列表

d. Copy list

        To copy a list, you can use the slicing operation or copy()method. For example:

original_list = [1, 2, 3]
copied_list = original_list[:]  # 使用切片操作复制列表
# 或
copied_list = original_list.copy()  # 使用copy()方法复制列表

2. Indexing and slicing

        Indexing and slicing of lists are common techniques for accessing and retrieving list elements. Indexing is used to get a single element, while slicing is used to get a subset of a list.

a. Index

        Each element in the list has a corresponding index, starting from 0, indicating the position of the element in the list. You can use an index to get an element at a specific position in a list.

my_list = ['apple', 'banana', 'orange']
print(my_list[0])  # 输出:'apple'
print(my_list[1])  # 输出:'banana'

b. Negative index

        Lists also support negative indexes, which count from the end of the list, with -1 representing the last element, -2 representing the penultimate element, and so on.

my_list = ['apple', 'banana', 'orange']
print(my_list[-1])  # 输出:'orange'
print(my_list[-2])  # 输出:'banana'

c. to slice

        Slicing is used to obtain a subset of a list by specifying the starting index and ending index. The slicing operation returns a new list containing the elements in the specified range.

my_list = ['apple', 'banana', 'orange', 'grape', 'mango']
print(my_list[1:4])     # 输出:['banana', 'orange', 'grape']
print(my_list[1:])      # 输出:['banana', 'orange', 'grape', 'mango']
print(my_list[1:-2])    # 输出:['banana', 'orange']
print(my_list[-1:-2])   # 输出:[]

  

3. Common operations (update, delete)

        List update and delete operations can be used to modify elements in the list or delete specific elements

a. Update a single element

my_list = ['apple', 'banana', 'orange']
my_list[1] = 'grape'
print(my_list)  # 输出:['apple', 'grape', 'orange']

b. Update slice

        To update a slice in a list, use the slice operator and assignment statement to assign a new list of elements to the specified slice position.

my_list = ['apple', 'banana', 'orange', 'grape', 'mango']
my_list[1:4] = ['kiwi', 'watermelon']
print(my_list)  # 输出:['apple', 'kiwi', 'watermelon', 'mango']

c. Delete a single element

        To remove a single element from a list, you use dela keyword and the index of the element you want to remove.

my_list = ['apple', 'banana', 'orange']
del my_list[1]
print(my_list)  # 输出:['apple', 'orange']

d. Delete the slice

        To remove a slice from a list, use the slice operator and delkeyword.

my_list = ['apple', 'banana', 'orange', 'grape', 'mango']
del my_list[1:4]
print(my_list)  # 输出:['apple', 'mango']

e. Incremental update

        Lists also support incremental update operations, by using +=operators to merge the new list with the original list.

my_list = ['apple', 'banana']
my_list += ['orange', 'grape']
print(my_list)  # 输出:['apple', 'banana', 'orange', 'grape']

f. Copy updates

original_list = ['apple', 'banana', 'orange']
original_list *= 2
print(original_list) # 输出:['apple', 'banana', 'orange', 'apple', 'banana', 'orange']

4. Commonly used functions

append(element): Adds an element to the end of the list.

my_list = [1, 2, 3]
my_list.append(4)
print(my_list)  # 输出: [1, 2, 3, 4]

extend(iterable): Adds elements of an iterable object to the end of the list.

my_list = [1, 2, 3]
another_list = [4, 5, 6]
my_list.extend(another_list)
print(my_list)  # 输出: [1, 2, 3, 4, 5, 6]

insert(index, element): Insert an element at the specified index position.

my_list = [1, 2, 3]
my_list.insert(1, 4)
print(my_list)  # 输出: [1, 4, 2, 3]

remove(element): Removes the first matching element from the list.

my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list)  # 输出: [1, 3, 2]

pop(index): Removes and returns the element at the specified index position.

my_list = [1, 2, 3]
removed_element = my_list.pop(1)
print(removed_element)  # 输出: 2
print(my_list)  # 输出: [1, 3]

index(element): Returns the index of the first occurrence of the specified element.

my_list = [1, 2, 3, 2]
index = my_list.index(2)
print(index)  # 输出: 1

count(element): Returns the number of times the specified element appears in the list.

my_list = [1, 2, 3, 2]
count = my_list.count(2)
print(count)  # 输出: 2

sort(): Sort the list in place, in ascending order.

my_list = [3, 1, 2]
my_list.sort()
print(my_list)  # 输出: [1, 2, 3]

reverse(): Reverse the list in place.

my_list = [1, 2, 3]
my_list.reverse()
print(my_list)  # 输出: [3, 2, 1]

copy(): Returns a shallow copy of the list.

my_list = [1, 2, 3]
new_list = my_list.copy()
print(new_list)  # 输出: [1, 2, 3]

5. Unpacking

        List unpacking is a technique that unpacks the elements of a list and assigns them to multiple variables. List unpacking makes it easy to assign elements in a list to separate variables for further processing. Here's a detailed explanation of list unpacking:

a. Basic unpacking

my_list = ['apple', 'banana', 'orange']
fruit1, fruit2, fruit3 = my_list
print(fruit1)  # 输出:'apple'
print(fruit2)  # 输出:'banana'
print(fruit3)  # 输出:'orange'

        In the above example, the unpacking operation is implemented by assigning the elements in the list to variables. When unpacking, the number of variables must match the number of elements in the list.

b. Extended unpacking

        If the length of the list exceeds the number of variables, you can use the extended unpacking operator (*) to assign the remaining elements to a variable. For example:

my_list = ['apple', 'banana', 'orange', 'grape', 'mango']
fruit1, fruit2, *remaining_fruits = my_list
print(fruit1)           # 输出:'apple'
print(fruit2)           # 输出:'banana'
print(remaining_fruits) # 输出:['orange', 'grape', 'mango']

        In the above example, the `remaining_fruits` variable receives the remaining elements via the extended unpacking operator, forming a new list.

6. Traverse       

a. Use a for loop

Use a for loop to iterate through all elements in a list. For example:

my_list = ['apple', 'banana', 'orange']
for fruit in my_list:
    print(fruit)

b. Use while loops and indexes

        Use a while loop combined with indexing to traverse the list. For example:

my_list = ['apple', 'banana', 'orange']
index = 0
while index < len(my_list):
    print(my_list[index])
    index += 1

c. Use the enumerate() function

        Use enumerate()a function to get both the index and the value of an element. For example:

my_list = ['apple', 'banana', 'orange']
for index, fruit in enumerate(my_list):
    print(index, fruit)

Guess you like

Origin blog.csdn.net/m0_63834988/article/details/132768246