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

如何在三维数据立方体中使用列表推导式进行值过滤?

Answer

Hey there! Let's figure out how to extend that list comprehension to handle your 3D image cube.

First, let's recap your working 2D code for a single image:

AM2 = [[x if x > 1e-5 else 0 for x in line] for line in AM[0]]

This iterates over each line in AM[0] (your first image), then each pixel value x in that line, replacing values below 1e-5 with 0.

For a 3D cube (where AM is a list of 2D images), you just need to add one more outer loop to iterate over each image in the cube. Here's the modified code:

AM_filtered = [[[x if x > 1e-5 else 0 for x in line] for line in image] for image in AM]

Let's break this down layer by layer:

  • The outermost loop for image in AM goes through every 2D image in your 3D cube.
  • The middle loop for line in image processes each row (line) of the current image.
  • The innermost loop for x in line checks each pixel value, replacing it with 0 if it's ≤1e-5, otherwise keeping the original value.

Example to visualize the structure

Suppose your 3D cube AM looks like this (simplified with small values):

AM = [
    [[0.0, 1.1e-5], [2.2e-5, 0.0]],  # Image 1
    [[3.3e-5, 0.0], [0.0, 4.4e-5]]   # Image 2
]

After applying the filtered list comprehension, AM_filtered would become:

[
    [[0, 1.1e-5], [2.2e-5, 0]],  # Image 1 (0s where values ≤1e-5)
    [[3.3e-5, 0], [0, 4.4e-5]]   # Image 2
]

Bonus: Faster alternative with NumPy (if applicable)

If you're working with large image datasets, list comprehensions can be slow. Using NumPy would make this operation much more efficient and concise:

import numpy as np

AM_np = np.array(AM)
AM_filtered_np = np.where(AM_np > 1e-5, AM_np, 0)

This vectorized operation does the same filtering in one line, and it's way faster for big 3D arrays.

Hope that solves your problem! 😊

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:22:48