Course Objective: To gain an in-depth understanding of the characteristics and applications of lists, tuples, dictionaries, and sets.
Core Content:
List Comprehensions and Generator Expressions
Common Operations and View Objects of Dictionaries
Mathematical Operations on Sets
Nested Data Structures and Practical Applications
1. List Comprehensions and Generator Expressions
List Comprehensions
List comprehensions provide a concise way to create new lists in a single line of code. They are more compact, faster, and more readable than traditional <span>for</span> loops.
The basic syntax is:<span>[expression for variable in iterable if condition]</span>.
Example: Filter out all even numbers from a list and generate a new list.
Traditional method:
old_list = [1, 2, 3, 4, 5, 6]
new_list = []
for item in old_list:
if item % 2 == 0:
new_list.append(item)
print(new_list) # Output: [2, 4, 6]
Generator Expressions
Generator expressions are very similar to list comprehensions, but they use parentheses <span>()</span> instead of square brackets <span>[]</span>.
The main difference is that list comprehensions create a complete list immediately and occupy memory, while generator expressions do not compute immediately; they generate a value only when needed. This is very advantageous when dealing with large datasets.
Example: Generate a generator containing the squares of numbers from 1 to 1,000,000.
List comprehension (uses a lot of memory):
large_list = [x**2 for x in range(1, 1000001)]
Generator expression (uses almost no memory):
large_gen = (x**2 for x in range(1, 1000001))
You can use the <span>next()</span> function or a <span>for</span> loop to retrieve values from the generator one by one.
2. Common Operations and View Objects of Dictionaries
Common Methods of Dictionaries
In addition to basic CRUD operations, dictionaries have some very useful methods:
<span>get(key, default)</span>: Safely retrieve a value. If the <span>key</span> does not exist, it will not raise an error but return the specified <span>default</span> value (default is <span>None</span>).
my_dict = {'a': 1, 'b': 2}
print(my_dict.get('c', 'key not found')) # Output: key not found
<span>setdefault(key, default)</span>: If the <span>key</span> exists, return its value; if not, add the <span>key</span> and <span>default</span> value to the dictionary and return the <span>default</span> value.
<span>update(another_dict)</span>: Update the current dictionary with key-value pairs from another dictionary.
View Objects of Dictionaries
The methods <span>dict.keys()</span>, <span>dict.values()</span>, and <span>dict.items()</span> return not lists, but dictionary view objects. These views are dynamic and will automatically update when the original dictionary changes.
my_dict = {'a': 1, 'b': 2}
keys_view = my_dict.keys()
print(keys_view) # Output: dict_keys(['a', 'b'])
my_dict['c'] = 3
print(keys_view) # Output: dict_keys(['a', 'b', 'c'])
3. Mathematical Operations on Sets
Sets are unordered collections of unique elements, making them ideal for performing mathematical operations such as intersection, union, and difference.
Assuming there are two sets:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
-
Union:
<span>|</span>or<span>union()</span>print(set1 | set2) # Output: {1, 2, 3, 4, 5, 6} -
Intersection:
<span>&</span>or<span>intersection()</span>print(set1 & set2) # Output: {3, 4} -
Difference:
<span>-</span>or<span>difference()</span>print(set1 - set2) # Elements in set1 but not in set2 # Output: {1, 2} -
Symmetric Difference:
<span>^</span>or<span>symmetric_difference()</span>print(set1 ^ set2) # Elements not shared by both sets # Output: {1, 2, 5, 6}
4. Nested Data Structures and Practical Applications
In practical programming, we often use nested data structures, such as lists containing dictionaries or dictionaries containing lists, to represent more complex data relationships.
Example: Use lists and dictionaries to store student information.
students = [
{'name': 'Zhang San', 'age': 20, 'courses': ['Python', 'Math']},
{'name': 'Li Si', 'age': 22, 'courses': ['English', 'C++']},
{'name': 'Wang Wu', 'age': 21, 'courses': ['Python', 'Physics']}
]
# Find all students who have taken the "Python" course
python_students = [student['name'] for student in students if 'Python' in student['courses']]
print(python_students) # Output: ['Zhang San', 'Wang Wu']
This example integrates lists, dictionaries, and list comprehensions, demonstrating how to efficiently handle complex data.
Post-Class Exercises
-
Use list comprehensions to create a new list containing the squares of all numbers between 1 and 20 that are divisible by 3.
-
Create a dictionary where
<span>'Zhang San'</span>has a score of 90 and<span>'Li Si'</span>has a score of 85. Then safely retrieve<span>'Wang Wu'</span>‘s score using the<span>get()</span>method, returning<span>0</span>if<span>'Wang Wu'</span>does not exist. -
Define two sets
<span>A = {1, 2, 3}</span>and<span>B = {3, 4, 5}</span>. Use mathematical operations on sets to find their union, intersection, and difference.
If you encounter any difficulties during the exercises or have any questions about today’s lesson, feel free to ask!