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

后端 未结 10 1058
予麋鹿
予麋鹿 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 05:54

    I'd start by writing a generator method:

    def grid_objects(alist, blist):
        for i in range(len(alist)):
            for j in range(len(alist[i])):
                yield(alist[i][j], blist[i][j])
    

    Then whenever you need to iterate over the lists your code looks like this:

    for (a, b) in grid_objects(alist, blist):
        if a.is_whatever():
            b.do_something()
    

提交回复
热议问题