python - 使用“扁平化”索引访问 2D 列表的好方法是什么?
问题描述
假设我们有一个 2D、3x3 的列表:
lst = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
list
使用“扁平”索引访问元素的推荐方法是什么?
我的意思是,我只有一个从 0 到 9 的数字。如何访问相应的list[i][j]
元素?
解决方案
您可以使用除法和取模来计算 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
推荐阅读
- python - CSV 到 SQL Server:批量导入噩梦(T-SQL 和/或 Pandas)
- angular-material-table - 有没有办法根据屏幕尺寸在 Angular Mat 表中应用“displayColumns”
- python-3.x - Python 3.7 操作系统模块“Windows 找不到 image.png”
- cs50 - 在 Caesar,Pset2 上遇到“分段错误”
- python - Django Web 应用程序中的 NoReverseMatch
- r - R:按条件选择数据框的元素
- android - 当我点击底部导航栏“收藏夹”时,删除了 ListTile 的尾随图标属性
- ios - Obj-C - 将 TableViewCell 从一个 TableView 拖放到另一个 TableView?
- forms - 如何使我的表单字段异步验证?
- python-3.x - Django 验证器