摘要:# Create a list of 5 None valuessize = 5empty_list = [None] * sizeprint(empty_list) # Output: [None, None, None, None, None]# Usef
空列表是许多 Python 程序的起点,无论您是收集用户输入、处理数据还是构建动态数据结构。让我们探索在 Python 中创建和使用空列表的所有方法。
创建空列表的最常见和可读的方法:
# Create a basic empty listempty_list = print(empty_list) # Output: print(len(empty_list)) # Output: 0print(type(empty_list)) # Output:创建空列表的另一种方法:
# Create empty list using the list constructorempty_list = listprint(empty_list) # Output: # Both methods create identical empty listslist1 = list2 = listprint(list1 == list2) # Output: True当您知道所需的尺寸时:
# Create a list of 5 None valuessize = 5empty_list = [None] * sizeprint(empty_list) # Output: [None, None, None, None, None]# Useful when you'll fill the list laterempty_list[2] = "Hello"print(empty_list) # Output: [None, None, 'Hello', None, None]创建列表列表时要小心:
# Wrong way - all inner lists reference the same listwrong_list = [] * 3wrong_list[0].append(1)print(wrong_list) # Output: [[1], [1], [1]] # Not what we wanted!# Right way - create independent empty listsright_list = [ for _ in range(3)]right_list[0].append(1)print(right_list) # Output: [[1], , ] # What we wantedclass 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 }# Usagetask_manager = TaskManagertask_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 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 = # Usageprocessor = DataProcessorprocessor.add_raw_data("1")processor.add_raw_data("2")processor.add_raw_data("invalid")processor.add_raw_data("3")processor.process_dataprint(f"Processed: {processor.processed_data}")print(f"Errors: {processor.errors}")import timedef 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 sizescompare_list_building(1000000)# Wrong waynumbers = [1, 2, 3, 4, 5]empty_list = for num in numbers: if num % 2 == 0: numbers.remove(num) # Modifies list during iteration # Right waynumbers = [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 listlist1 = list2 = list1list1.append(1)print(list2) # Output: [1] # list2 is affected# Right way - create a new empty listlist1 = list2 = # or list2 = listlist1.append(1)print(list2) # Output: # list2 is independentfrom typing import List, TypeVarT = TypeVar('T')def create_typed_list(list_type: Type[T]) -> List[T]: """Create an empty list that will contain specific types.""" return # Usageint_list: List[int] = create_typed_list(int)str_list: List[str] = create_typed_list(str)# Type hints help catch errors during developmentint_list.append(1) # OKstr_list.append("hello") # OK# int_list.append("wrong") # Type checker would flag this通过了解这些方法及其适当的使用案例,您可以选择正确的方法来在 Python 程序中创建和处理空列表。请记住,在处理大型数据集时要考虑内存使用情况和性能。
来源:自由坦荡的湖泊AI一点号