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

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

    Generator expressions and izip from itertools module will do very nicely here:

    from itertools import izip
    for a, b in (pair for (aline, bline) in izip(alist, blist) 
                 for pair in izip(aline, bline)):
        if a.isWhatever:
            b.doSomething()
    

    The line in for statement above means:

    • take each line from combined grids alist and blist and make a tuple from them (aline, bline)
    • now combine these lists with izip again and take each element from them (pair).

    This method has two advantages:

    • there are no indices used anywhere
    • you don't have to create lists with zip and use more efficient generators with izip instead.

提交回复
热议问题