You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将嵌套列表所有元素替换为1?Python递归函数问题排查

Hey, let's work through why your recursive function isn't producing the expected result!

The Root Issue

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.

Fixed Solutions

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]
Test It Out

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]]]
Quick Notes
  • I swapped type(x) == list for isinstance(x, list)—this is a better practice because it works correctly if you ever use a subclass of list.
  • 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_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:34:31