列表列表中值的最小和最大索引

时间:2021-05-30 21:48:43

标签: python nested-lists

我有一个 3D 列表列表,其项目可以是任何有限选择:

list_of_lists = [[[0, 0], [0, 1]], [[0, 0], [1, 1]], [[0, 0], [0, 0]]]

我想确定每个出现项的所有 3 个维度中的最小和最大索引。

(我不想找到最小和最大项目的索引,这似乎是一个更常见的问题。)

输出应该是:

# value: [min_x, max_x, min_y, max_y, min_z, max_z]
0: [0, 1, 0, 1, 0, 2]
1: [0, 1, 1, 1, 0, 1] # 1 does not occur in any list #0 of second dimension and not in list #2 of the highest dimension

其中 x 表示列表列表的最低维度,y 表示第二个维度,z 表示最高维度。

2 个答案:

答案 0 :(得分:0)

这就是我现在这样做的方式(抱歉,这里没有完整的代码,因为这将包含大量不会向问题添加信息的行)。但是,代码非常不习惯。

indices_min_max 是一个字典,其键是列表列表中的值,其各自的值初始化为 None。

代码迭代列表列表的单个项目,x_value、y_value 和 z_value 是每个项目在 3 维中的坐标。

if indices_min_max[value] == None:
    indices_min_max[value] = [x_value, x_value, y_value, y_value, z_value, z_value]
else:
    if x_value < indices_min_max[value][0]:
        organs_min_max_dict[value][0] = x_value

    if x_value > indices_min_max[value][1]:
        organs_min_max_dict[value][1] = x_value

    if y_value < indices_min_max[value][2]:
        organs_min_max_dict[value][2] = y_value

    if y_value > indices_min_max[value][3]:
        organs_min_max_dict[value][3] = y_value

    if z_value < indices_min_max[value][4]:
        organs_min_max_dict[value][4] = z_value

    if z_value > indices_min_max[value][5]:
        organs_min_max_dict[value][5] = z_value

答案 1 :(得分:0)

首先,你的维度是倒退的。您的 list_of_lists 的形状是 (3, 2, 2),而不是 (2, 2, 3)(至少在我习惯的系统中,例如在 NumPy 中使用)。

其次,将最小值和最大值交错对我来说真的很困惑,所以我打算以不同的方式安排所需的输出:

{0: {'min': [0, 0, 0], 'max': [2, 1, 1]},
 1: {'min': [0, 1, 0], 'max': [1, 1, 1]}}

另一方面,您可能会发现交错维度令人困惑,这是完全有效的。

最后,如果您的实际数据很长,此解决方案可能会相对较慢。在这种情况下,请考虑使用 NumPy 使其更快。由于 NumPy 是专门为多维数据设计的,因此解决方案最终可能会更简洁。


使用 enumerate() 获取沿每个轴的索引,并将每个坐标与之前保存的最小值/最大值进行比较。

list_of_lists = [
    [[0, 0], [0, 1]],
    [[0, 0], [1, 1]],
    [[0, 0], [0, 0]]]

d = {}
props = {'min': min, 'max': max}  # Properties we're looking for
for x, row in enumerate(list_of_lists):
    for y, col in enumerate(row):
        for z, elem in enumerate(col):
            c = (x, y, z)
            if elem not in d:
                d[elem] = {p: list(c) for p in props}
                continue

            for p, f in props.items():
                L = d[elem][p]
                L[:] = (f(old, new) for old, new in zip(L, c))