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

后端 未结 10 1040
予麋鹿
予麋鹿 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:03

    If a.isWhatever is rarely true you could build an "index" once:

    a_index = set((i,j) 
                  for i,arow in enumerate(a) 
                  for j,a in enumerate(arow) 
                  if a.IsWhatever())
    

    and each time you want something to be done:

    for (i,j) in a_index:
        b[i][j].doSomething()
    

    If a changes over time, then you will need to keep the index up-to-date. That's why I used a set, so items can be added and removed fast.

提交回复
热议问题