【问题标题】:Python function list parameter variable structurePython函数列表参数变量结构
【发布时间】:2020-06-11 20:21:39
【问题描述】:

我在使用以下功能时遇到问题。我无法弄清楚routes 参数结构。

def show_image(data, routes=[]):
    '''
    Given a list of lists of integers "data",
    and an optional list of boolean list of lists "routes",
    show the data as an image and overlay the routes on the image in red.
    '''
    image_data = [x[:] for x in data]
    for i in range(len(image_data)):
        for j in range(len(image_data[i])):
            image_data[i][j] = [image_data[i][j]] * 3
            if any(route[i][j] for route in routes):
                image_data[i][j] = [255, 0, 0]
    io.imshow(np.array(image_data, dtype=np.uint8))
    io.show()

我有数据参数工作,但我不确定routes = []。我知道它需要一个"list of boolean list of lists",我假设它是这样的:

[[True, True], [False,False]]

有人可以给我一些虚拟的data 参数来看看它是如何工作的吗?谢谢

【问题讨论】:

    标签: python function types parameters boolean


    【解决方案1】:

    routes 应该是一个 3 维列表。 routes 的每个元素都应该是一个与data 具有相同维度的二维列表。

    您可以通过生成器来判断这一点

    route[i][j] for route in routes
    

    routeroutes 的元素之一,您必须能够使用 2 个索引访问它。 ij 迭代 image_data(最初是 data 的副本)的行和列索引。

    对于data中的每个像素,如果routes的任何一个对应元素是True,则将像素值替换为[255, 0, 0]

    这是一个例子:

    image =   [[1,     2,     3],     [4,     5,     6],     [7,     8,     9]]
    routes = [[[True,  False, True ], [False, False, False], [False, False, True ]],
              [[False, False, False], [False, False, False], [False, False, True]]]
    show_image(image, routes)
    

    image 是 3x3 图像,routes 是两个 3x3 布尔值列表的列表。我已经垂直排列了相应的元素。如果您阅读该列并看到任何 True 值,则该像素将替换为 [255, 0, 0],否则将是 [value, value, value],其中 value 是原始 image 列表中的值(例如 @987654344 @ 表示第一行的第二个像素)。

    【讨论】:

    • 你能给我一个数据和路由的虚拟参数的例子吗?
    • 我已在答案中添加了详细信息。
    • 正是我需要让事情正常工作。谢谢@barmar!
    猜你喜欢
    • 1970-01-01
    • 2022-12-07
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    相关资源
    最近更新 更多