一文掌握如何在 Python 中创建空列表
空列表是许多 Python 程序的起点,无论您是收集用户输入、处理数据还是构建动态数据结构。让我们探索在 Python 中创建和使用空列表的所有方法。
创建空列表的基本方法
使用方括号
创建空列表的最常见和可读的方法:
# Create a basic empty list
empty_list = []
print(empty_list) # Output: []
print(len(empty_list)) # Output: 0
print(type(empty_list)) # Output:
使用 list() 构造函数
创建空列表的另一种方法:
# Create empty list using the list constructor
empty_list = list()
print(empty_list) # Output: []
# Both methods create identical empty lists
list1 = []
list2 = list()
print(list1 == list2) # Output: True
创建特定大小的列表
无的预分配列表
当您知道所需的尺寸时:
# Create a list of 5 None values
size = 5
empty_list = [None] * size
print(empty_list) # Output: [None, None, None, None, None]
# Useful when you'll fill the list later
empty_list[2] = "Hello"
print(empty_list) # Output: [None, None, 'Hello', None, None]
空列表的列表
创建列表列表时要小心:
# Wrong way - all inner lists reference the same list
wrong_list = [[]] * 3
wrong_list[0].append(1)
print(wrong_list) # Output: [[1], [1], [1]] # Not what we wanted!
# Right way - create independent empty lists
right_list = [[] for _ in range(3)]
right_list[0].append(1)
print(right_list) # Output: [[1], [], []] # What we wanted
实际应用
构建任务管理器
class TaskManager:
def __init__(self):
# Initialize empty lists for different priority tasks
self.high_priority = []
self.medium_priority = []
self.low_priority = []
def add_task(self, task, priority='medium'):
if priority == 'high':
self.high_priority.append(task)
elif priority == 'low':
self.low_priority.append(task)
else:
self.medium_priority.append(task)
def get_all_tasks(self):
return {
'high': self.high_priority,
'medium': self.medium_priority,
'low': self.low_priority
}
# Usage
task_manager = TaskManager()
task_manager.add_task("Fix critical bug", "high")
task_manager.add_task("Write documentation")
task_manager.add_task("Update readme", "low")
print(task_manager.get_all_tasks())
分数跟踪系统
class ScoreTracker:
def __init__(self, number_of_players):
# Create empty score lists for each player
self.scores = [[] for _ in range(number_of_players)]
def add_score(self, player_id, score):
if 0 <= player_id < len(self.scores):
self.scores[player_id].append(score)
def get_average(self, player_id):
if not self.scores[player_id]:
return 0
return sum(self.scores[player_id]) / len(self.scores[player_id])
# Usage
game = ScoreTracker(3) # 3 players
game.add_score(0, 10)
game.add_score(0, 15)
game.add_score(1, 20)
print(f"Player 0 average: {game.get_average(0)}") # Output: 12.5
print(f"Player 1 average: {game.get_average(1)}") # Output: 20.0
print(f"Player 2 average: {game.get_average(2)}") # Output: 0.0
数据处理管道
class DataProcessor:
def __init__(self):
self.raw_data = []
self.processed_data = []
self.errors = []
def add_raw_data(self, data):
self.raw_data.append(data)
def process_data(self):
for item in self.raw_data:
try:
# Example processing: convert to float and square
processed = float(item) ** 2
self.processed_data.append(processed)
except ValueError as e:
self.errors.append(f"Error processing {item}: {str(e)}")
# Clear raw data after processing
self.raw_data = []
# Usage
processor = DataProcessor()
processor.add_raw_data("1")
processor.add_raw_data("2")
processor.add_raw_data("invalid")
processor.add_raw_data("3")
processor.process_data()
print(f"Processed: {processor.processed_data}")
print(f"Errors: {processor.errors}")
内存管理和性能
预先分配列表与增长列表
import time
def compare_list_building(size):
# Method 1: Growing list
start_time = time.time()
growing_list = []
for i in range(size):
growing_list.append(i)
growing_time = time.time() - start_time
# Method 2: Pre-allocated list
start_time = time.time()
fixed_list = [None] * size
for i in range(size):
fixed_list[i] = i
fixed_time = time.time() - start_time
print(f"Growing list time: {growing_time:.4f}s")
print(f"Fixed list time: {fixed_time:.4f}s")
# Test with different sizes
compare_list_building(1000000)
节省内存的列表创建
def create_large_sequence(n):
# Bad: Creates full list in memory
# numbers = list(range(n))
# Good: Creates generator object
numbers = (i for i in range(n))
return numbers
# Usage
large_sequence = create_large_sequence(1000000)
# Process items one at a time
for num in large_sequence:
# Process num
pass
要避免的常见错误
迭代时修改列表
# Wrong way
numbers = [1, 2, 3, 4, 5]
empty_list = []
for num in numbers:
if num % 2 == 0:
numbers.remove(num) # Modifies list during iteration
# Right way
numbers = [1, 2, 3, 4, 5]
odd_numbers = []
for num in numbers[:]: # Create a copy for iteration
if num % 2 != 0:
odd_numbers.append(num)
列出参考问题
# Wrong way - both variables reference the same list
list1 = []
list2 = list1
list1.append(1)
print(list2) # Output: [1] # list2 is affected
# Right way - create a new empty list
list1 = []
list2 = [] # or list2 = list()
list1.append(1)
print(list2) # Output: [] # list2 is independent
检查空列表
# Less pythonic way
empty_list = []
if len(empty_list) == 0:
print("List is empty")
# More pythonic way
if not empty_list:
print("List is empty")
特殊情况
特定于类型的空列表
from typing import List, TypeVar
T = TypeVar('T')
def create_typed_list(list_type: Type[T]) -> List[T]:
"""Create an empty list that will contain specific types."""
return []
# Usage
int_list: List[int] = create_typed_list(int)
str_list: List[str] = create_typed_list(str)
# Type hints help catch errors during development
int_list.append(1) # OK
str_list.append("hello") # OK
# int_list.append("wrong") # Type checker would flag this
通过了解这些方法及其适当的使用案例,您可以选择正确的方法来在 Python 程序中创建和处理空列表。请记住,在处理大型数据集时要考虑内存使用情况和性能。