How can I, in python, iterate over multiple 2d lists at once, cleanly?

后端 未结 10 1047
予麋鹿
予麋鹿 2021-02-05 05:15

If I\'m making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to ite

10条回答
  •  心在旅途
    2021-02-05 06:05

    If the two 2D-lists remain constant during the lifetime of your game and you can't enjoy Python's multiple inheritance to join the alist[i][j] and blist[i][j] object classes (as others have suggested), you could add a pointer to the corresponding b item in each a item after the lists are created, like this:

    for a_row, b_row  in itertools.izip(alist, blist):
        for a_item, b_item in itertools.izip(a_row, b_row):
            a_item.b_item= b_item
    

    Various optimisations can apply here, like your classes having __slots__ defined, or the initialization code above could be merged with your own initialization code e.t.c. After that, your loop will become:

    for a_row in alist:
        for a_item in a_row:
            if a_item.isWhatever():
                a_item.b_item.doSomething()
    

    That should be more efficient.

提交回复
热议问题