Table of contents
1 Syntax structure of loop
In Python, a loop is a control structure used to repeatedly execute a section of code until a specific condition is met. There are two loop structures in Python: for
loop and while
loop.
for
Loop:for
Loop is used to iterate over the elements in iterable objects (such as lists, tuples, dictionaries, sets, etc.). Its grammatical structure is as follows:
for 变量 in 可迭代对象:
循环体(要重复执行的代码)
For example, iterate over a list and print each element:
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
while
Loop:while
A loop repeatedly executes a block of code while a given condition is true. Its grammatical structure is as follows:
while 条件:
循环体(要重复执行的代码)
For example, the counter starts at 0 and increments by 1 each time through the loop until the counter reaches 5:
counter = 0
while counter < 5:
print(counter)
counter += 1
for
Both loops and while
loops can be used with the break
and continue
statements to give greater control over the looping implement. The break
statement is used to terminate the loop early, while the continue
statement is used to skip the current iteration and enter the next loop.
2 Examples of break and continue
break
and continue
are keywords in Python used to control the flow of a loop. Examples of each are given below:
-
break
: Used to jump out of the current loop and no longer execute the remaining code in the loop body.for i in range(10): if i == 5: break print(i)
In this example, the loop iterates over the integers from 0 to 9. When i
is equal to 5, the break
statement will be executed, the loop will be jumped out, and the value of i
will no longer be printed. Therefore, this loop will only print integers from 0 to 4.
-
continue
: Used to skip the remaining code of the current loop and directly enter the next loop.for i in range(10): if i % 2 == 0: continue print(i)
In this example, the loop iterates over the integers from 0 to 9. When i
is an even number, the continue
statement will be executed, skipping the remaining code of the current loop and entering the next loop directly. Therefore, this loop will only print odd numbers from 1 to 9.
By using break
and continue
, we can control the execution flow of the loop more flexibly to meet different needs.
3 iterable objects
In Python, an iterable object (Iterable) refers to an object that contains the __iter__()
method or the __getitem__()
method. This means that iterative operations can be performed on these objects, such as traversing their elements in a loop. for
Here are some common iterable objects:
- List: Example
[1, 2, 3, 4, 5]
. - Tuple: For example
(1, 2, 3, 4, 5)
. - String: For example
'hello, world'
. - Set: Example
{1, 2, 3, 4, 5}
. - Dictionary: For example
{'a': 1, 'b': 2, 'c': 3}
. - Generator: Examples
(x**2 for x in range(5))
.
Iterable objects allow us to easily iterate over their elements infor
loops without having to worry about the underlying implementation details. This makes Python code more concise and readable.
4 list
List is a data structure in Python. It is an ordered collection of elements that can contain any number of elements. The elements in the list can be different types of data, such as integers, floating point numbers, strings, Boolean values, etc. Lists are mutable, which means we can modify the elements in the list, add or remove elements.
The list is represented by square brackets[]
and its elements are separated by commas,
. For example:
my_list = [1, 2, 3, 4, 5]
Lists have the following common operations:
-
Get elements: Access elements in a list by index. Indexing starts at 0, and a negative index means counting from the end. For example:
first_element = my_list[0] # 获取第一个元素 last_element = my_list[-1] # 获取最后一个元素
-
Add element: Add an element to the end of the list. For example:
my_list.append(6) # 在列表末尾添加元素6
-
Insert element: Insert an element at the specified index. For example:
my_list.insert(1, 7) # 在索引1处插入元素7
-
Remove element: Remove the element at the specified index from the list. For example:
my_list.pop(1) # 删除索引1处的元素
-
Modify elements: Modify elements in the list by index. For example:
my_list[0] = 0 # 将索引0处的元素修改为0
-
List comprehensions: quickly create new lists using concise syntax. For example:
squares = [x**2 for x in range(1, 6)] # 创建一个包含1到5的平方数的新列表
-
List sorting: Sort the elements of a list. For example:
my_list.sort() # 对列表的元素进行升序排序
-
List slicing: Get a part of a list. For example:
sublist = my_list[1:4] # 获取索引1到3的元素组成的新列表
-
List length: Get the number of elements in the list. For example:
length = len(my_list) # 获取列表的长度
-
List traversal: Use
for
to loop through each element in the list. For example:for element in my_list: print(element)
Lists are one of the most commonly used data structures in Python, and they are very convenient and flexible when processing data.
5-tuple
Tuple is a data structure in Python. It is an immutable, ordered collection of elements. The elements in a tuple can be of any data type, such as integers, floating point numbers, strings, lists, tuples, sets, etc. Tuples are usually used to store a set of related or unrelated data to facilitate subsequent processing and analysis.
Tuples can be created in the following ways:
-
Use parentheses
()
to create an empty tuple, then add elements:my_tuple = () my_tuple = (1, 2, 3, 4, 5)
-
Create a tuple using the
tuple()
function, passing multiple values as arguments to the function:my_tuple = tuple() my_tuple = tuple([1, 2, 3, 4, 5])
-
Convert the list to a tuple using the
tuple()
method of the list:my_list = [1, 2, 3, 4, 5] my_tuple = tuple(my_list)
The main operations of tuples include:
-
Get elements in a tuple: Use indexing (starting from 0) or slicing operations to get elements in a tuple. For example:
first_element = my_tuple[0] second_element = my_tuple[1] third_element = my_tuple[2:]
-
Determine whether the tuple is empty: Use the
not
operator andlen()
function to determine whether the tuple is empty. For example:if not my_tuple: print('The tuple is empty') else: print('The tuple is not empty')
-
Get the length of a tuple: Use the
len()
function to get the length of a tuple. For example:length = len(my_tuple)
-
Loop through tuples: Use
for
to loop through all elements in a tuple. For example:for element in my_tuple: print(element)
-
Join Tuples: Use the
+
operator to join two or more tuples. For example:tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) combined_tuple = tuple1 + tuple2
Tuples are very useful when working with data, especially when you need to store and access ordered data sets. In contrast to lists, tuples are immutable, which means that once a tuple is created, its contents cannot be modified. This makes tuples safer and easier to handle in some situations.
6 Application scenarios of lists and tuples
In Python, tuples and lists are commonly used data structures. They have the following differences:
- Mutability: Lists are mutable and elements can be modified, added and deleted; tuples are immutable and elements cannot be modified, added or deleted.
- Syntax: Lists are represented by square brackets
[]
, and tuples are represented by brackets()
. - Performance: Because tuples are immutable, they are stored more efficiently in memory and are faster to access when working with large amounts of data.
Based on these differences, we can choose to use tuples or lists according to actual needs:
-
Use tuples when you need to store immutable data. For example, a date (year, month, day) can be represented as a tuple because dates are immutable.
date = (2022, 10, 1)
-
Use lists when you need to store mutable data. For example, a list of items in a shopping cart can be represented as a list because items in the shopping cart can be added, removed, or modified.
shopping_cart = ['apple', 'banana', 'orange']
-
Use lists when you need to modify, add, or delete data. For example, when processing user-entered data, we may need to add, delete or modify data.
user_data = ['Alice', 'Bob', 'Charlie'] user_data.append('David') # 添加新用户 user_data.remove('Bob') # 删除用户 user_data[0] = 'Alicia' # 修改用户名
-
Tuples are used when fast access and iterative operations on data are required. For example, using tuples can improve performance when dealing with large amounts of static data.
countries = ('China', 'USA', 'Japan', 'Germany', 'France') for country in countries: print(country)
In short, depending on the actual needs and the variability of the data, we can choose to use tuples or lists to store and operate data.
7 collection
Set is a data structure in Python. It is an unordered and non-repeating collection of elements. The elements in the collection can be any hashable type, such as integers, floating point numbers, strings, tuples, etc. The main operations of collections include adding, deleting, checking whether elements exist, calculating the number of elements, etc.
Collections can be created in the following ways:
-
Use curly braces
{}
to create an empty collection and then add elements:my_set = { 1, 2, 3, 4, 5}
-
Create an empty collection using the
set()
function and then add elements:my_set = set() my_set.add(1) my_set.add(2) my_set.add(3) my_set.add(4) my_set.add(5)
-
Create a set using set operators, such as
|
(union),&
(intersection),-
( Difference set), etc.:set1 = { 1, 2, 3, 4, 5} set2 = { 4, 5, 6, 7, 8} # 并集 union_set = set1 | set2 print(union_set) # {1, 2, 3, 4, 5, 6, 7, 8} # 交集 intersection_set = set1 & set2 print(intersection_set) # {4, 5} # 差集 difference_set = set1 - set2 print(difference_set) # {1, 2, 3}
The main operations of collections include:
-
Add element: Use the
add()
method to add an element to the collection.my_set.add(6)
-
Delete element: Use the
remove()
method to delete the specified element from the collection. If the element does not exist,KeyError
is raised.my_set.remove(1)
-
Check if the element exists: Use the
in
keyword or thecontains()
method to check if the element is in the collection.if 5 in my_set: print('5 is in the set') elif 6 in my_set: print('6 is in the set') else: print('Neither 5 nor 6 is in the set')
-
Count the number of elements: Use the
len()
function or thesize()
method to get the number of elements in the set.num_elements = len(my_set)
-
Set operations: Use set operators (such as
|
,&
,-
, etc.) to perform operations between sets .union_set = set1 | set2 intersection_set = set1 & set2 difference_set = set1 - set2
Sets are very useful when processing data, especially in scenarios where you need to remove duplicate elements or perform set operations.
8 dictionary
Dictionary is a data structure in Python. It is an unordered, mutable, key-value data type. Each key in the dictionary is a unique identifier, and the corresponding value can be any data type, such as integers, floating point numbers, strings, lists, tuples, sets, etc. Keys and values in a dictionary are separated by a colon (:), and each key-value pair is separated by a comma (,).
The main operations of the dictionary include:
-
Create a dictionary: Use curly braces
{}
to create an empty dictionary and add key-value pairs. For example:my_dict = { 'name': 'Alice', 'age': 30, 'city': 'New York'}
-
Get the value in the dictionary: Use the key as an index to get the value in the dictionary. For example:
name = my_dict['name'] age = my_dict.get('age')
-
Modify values in a dictionary: Modify values in a dictionary using keys as indexes. For example:
my_dict['age'] = 31
-
Add key-value pair: Adds a new key-value pair to the dictionary using the key as an index. If the key already exists, the original value is overwritten. For example:
my_dict['gender'] = 'female'
-
Delete key-value pair: Delete the specified key-value pair from the dictionary using the key as an index. If the key does not exist,
KeyError
is raised. For example:del my_dict['age']
-
Check if the key exists: Use the
in
keyword or thehas_key()
method to check if the key is in the dictionary. For example:if 'name' in my_dict: print('name is in the dictionary') elif 'age' in my_dict: print('age is in the dictionary') else: print('Neither name nor age is in the dictionary')
-
Get all keys in the dictionary: Use the
keys()
method to get all keys in the dictionary. For example:keys = my_dict.keys()
-
Get all values in the dictionary: Use the
values()
method to get all the values in the dictionary. For example:values = my_dict.values()
-
Get key-value pairs in the dictionary: Use the
items()
method to get all key-value pairs in the dictionary. For example:items = my_dict.items()
Dictionaries are very useful when working with data, especially in scenarios where complex data structures need to be stored and retrieved.
9 generator
A generator is a special type of iterator that allows you to create an iterable object that dynamically generates new values on each iteration, rather than precomputing all the values and storing them in memory. Generators are useful in scenarios where you are dealing with large amounts of data or need to generate data on demand, as they save memory and improve performance.
The generator uses theyield
keyword to return a value and pause execution on the next call until the next value is requested again. This allows the generator to dynamically generate values when needed, rather than generating them all at once.
Here is a simple generator example for generating the first n square numbers:
def square_generator(n):
for i in range(1, n+1):
yield i**2
# 使用生成器
for square in square_generator(5):
print(square)
In this example, the square_generator
function is a generator that returns each square number using the yield
keyword. When we use a generator in a for
loop, it dynamically generates the next square number on each iteration instead of calculating all the square numbers at once. This means that the generator can save memory when processing large amounts of data.