索引嵌套列表 [英] Indexing a nested list

查看:111
本文介绍了索引嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写一个python程序,其中大量使用索引迷宫,如结构。我目前已经将列表设置为包含单独的嵌套列表,每个嵌套列表代表迷宫的一行,我对其进行索引,因此Maze [0] [1]用于第一行和第二列的网格迷宫的位置。如果我将迷宫转换为单个列表,同时跟踪行的长度,并相应地移动列表,我的程序是否会运行得更快。如果我使用Maze [(0 * row_length)+1]而不是Maze [0] [1],我会收到多少速度提升?

I am currently writing a python program which involves heavy use of indexing a maze, like structure. I currently have it set up the list as containing separate nested lists each representing one line of the maze, which I index like so Maze[0][1] for the position of the grid maze which is on the first row and second column. Would my program run faster if I converted the maze to a single list while keeping track of how long a row is, and moving through the list accordingly. How much more of a speed boost would I receive if I utilized Maze[(0*row_length)+1] instead of Maze[0][1]?

推荐答案

不要打扰。这几乎肯定不是你的瓶颈,管理索引计算和行长度变量是不值得的。

Don't bother. This is almost certainly not your bottleneck, and it's not worth the headache of managing the indexing calculations and the row length variable.

时间数据:

>>> timeit("a[1][2]", setup="a = [[0]*5 for _ in xrange(4)]")
0.09207810811146055
>>> timeit("a[1*5+2]", setup="a = [0]*5*4")
0.06518904043262097
>>> timeit("a[1*row_length+2]", setup="a = [0]*5*4; row_length=5")
0.11411290029380439

当行长度为内联常量时,展平列表获胜,但当行长度为全局变量时,它会丢失。如果你试图通过展平列表来获得优势,那么你将浪费大量时间来管理索引,除非你非常小心地执行它,否则它甚至可能会运行得更慢。不要打扰。

The flattened list won when the row length was an inlined constant, but it lost when the row length was a global variable. If you try to gain an advantage by flattening your list, you will waste a ton of time managing the indexes, and unless you do it very carefully, it may even run slower. Don't bother.

这篇关于索引嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆