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:
- The outer loop iterates over each sublist in your original
vals - The inner loop filters each element in the current sublist, only keeping elements that aren't in
targets
- The outer loop iterates over each sublist in your original
- Converting
targetsto asetis 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
相关产品推荐
相关产品推荐

