首页 > 解决方案 > 使用“扁平化”索引访问 2D 列表的好方法是什么?

问题描述

假设我们有一个 2D、3x3 的列表:

lst =  [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]

list使用“扁平”索引访问元素的推荐方法是什么?

我的意思是,我只有一个从 0 到 9 的数字。如何访问相应的list[i][j]元素?

标签: pythonlist

解决方案


您可以使用除法和取模来计算 2D 坐标(仅在所有子列表具有相同大小时才有效)

def get_item(lst,i):    
    return(lst[i//len(lst[0])][i%len(lst[0])])

请注意,展平列表以访问项目是O(n**2)复杂的,而这种方法是O(1).

如果子列表长度可变,则必须先找到子列表,并且不能使用除法。但是一旦找到正确的子列表,您就可以O(1)访问:

lst = [[1, 2, 3, 4],
        [5, 6],
        [7,8,9,10]]

def get_item(lst,i):
    current = 0
    for sublist in lst:
        index = i - current
        if 0 <= index < len(sublist):
            return sublist[index]
        current += len(sublist)
    raise Exception("index out of range {}".format(i))

print(get_item(lst,0),get_item(lst,6),get_item(lst,9))

印刷:1 7 10


推荐阅读