如何将嵌套列表所有元素替换为1?Python递归函数问题排查
Hey, let's work through why your recursive function isn't producing the expected result!
The core problem here is that when you do x = 1 in your loop, you're only reassigning the local variable x—you aren't actually modifying the element in the original nested list. The x in your loop is just a temporary reference to the list element; changing its value doesn't update the position in the parent list.
Here are two reliable ways to fix this:
Solution 1: Modify the List In-Place Using Indices
Instead of iterating over elements directly, loop through their indices so you can update the original list directly:
def vnor(tab): for i in range(len(tab)): if isinstance(tab[i], int): tab[i] = 1 elif isinstance(tab[i], list): vnor(tab[i]) return tab
Solution 2: Return a New Nested List (Functional Style)
If you prefer not to mutate the original list, use a list comprehension with recursion to build a fresh, updated structure:
def vnor(tab): return [vnor(item) if isinstance(item, list) else 1 for item in tab]
Let's run this with your sample input:
tab = [[[0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]] print(vnor(tab))
You'll get exactly the output you wanted:
[[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]]
- I swapped
type(x) == listforisinstance(x, list)—this is a better practice because it works correctly if you ever use a subclass oflist. - Solution 1 modifies your original list in place, while Solution 2 creates a new one. Pick whichever fits your use case better!
内容的提问来源于stack exchange,提问作者zivanska_

