Advent of Code第8天:列表复制失效致指令修改异常问询
Ah, I see exactly what's going on here! This is a classic shallow vs deep copy problem—super common when working with nested lists in Python, and it trips up a lot of people.
Why Your Current Copy Methods Aren't Working
All the copy approaches you tried (list(o_list), o_list.copy(), o_list[:], copy.copy(o_list)) are shallow copies. Here's the catch: your o_list isn't just a flat list—it's a list containing sublists (each instruction is something like ['jmp', +3]).
Shallow copying only creates a new outer list, but the inner sublists are still references to the same objects in memory as the original list. So when you run n_list[j][0] = 'nop', you're actually modifying the sublist directly in the original o_list—that's why your changes carry over to the next iteration!
Fixing the Problem
You need to create a deep copy of the list, which will duplicate every nested element instead of just the outer container. Here are two straightforward ways to do this:
Option 1: Use copy.deepcopy() (Most Direct)
Import the copy module and use its deepcopy function to fully replicate the nested structure:
import copy def fixError(o_list): jmpPositions = [] for jmp in range(len(o_list)): # Collect all positions with 'jmp' instructions if o_list[jmp][0] == 'jmp': jmpPositions.append(jmp) print(jmpPositions) for j in jmpPositions: accumulator = 0 # Avoid global variables by using a local one # Create a fully independent copy of the entire list structure n_list = copy.deepcopy(o_list) print('\nBefore correction', n_list) print('replacing at', j) n_list[j][0] = 'nop' print('After correction ', n_list) # Don't forget to add logic here to run the corrected sequence and check if it terminates properly! fixError(instructions)
Option 2: Manually Copy Sublists (No Extra Module Needed)
If you don't want to import the copy module, you can iterate over the original list and create a new copy of each sublist individually:
def fixError(o_list): jmpPositions = [] for jmp in range(len(o_list)): if o_list[jmp][0] == 'jmp': jmpPositions.append(jmp) print(jmpPositions) for j in jmpPositions: accumulator = 0 # Create a new list where each sublist is a separate copy n_list = [inst.copy() for inst in o_list] print('\nBefore correction', n_list) print('replacing at', j) n_list[j][0] = 'nop' print('After correction ', n_list) # Add your sequence execution/check logic here fixError(instructions)
Quick Side Note
Using global accumulator isn't the best practice—it makes your code harder to debug and reuse. Instead, keep accumulator as a local variable, or create a helper function that runs the instruction sequence and returns the accumulator value once it finishes (or loops infinitely).
内容的提问来源于stack exchange,提问作者Iscariot




