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

Python二维列表移除目标元素后保持二维结构的实现咨询

Fixing the 2D Structure Preservation in Your remove_vals Function

Got it, let's get this sorted out. The issue with your current remove_vals function is that it's flattening the 2D list into a 1D result when you only want to filter elements within each sublist while keeping the overall 2D structure intact.

Here's the Modified Code

def remove_vals(vals, targets):
    # Convert targets to a set for faster lookups (great for larger target lists)
    target_set = set(targets)
    # Nested list comprehension to filter each sublist individually
    return [[num for num in sublist if num not in target_set] for sublist in vals]

Let's Test It Out

If you run this with your inputs:

vals = [[2, 2, 2, 2, 2, 2, 2], [2, 2, 2, 3], [2, 3, 4]]
targets = [2]
print(remove_vals(vals, targets))

You'll get the desired output:

[[], [3], [3, 4]]

Why This Works

  • Instead of collecting all valid elements into a single 1D list, we use a nested list comprehension:
    1. The outer loop iterates over each sublist in your original vals
    2. The inner loop filters each element in the current sublist, only keeping elements that aren't in targets
  • Converting targets to a set is a small optimization—checking membership in a set is O(1) vs O(n) for a list, which makes a big difference if your target list grows large.

内容的提问来源于stack exchange,提问作者Danny M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 15:32:38