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

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

    If anyone is interested in performance of the above solutions, here they are for 4000x4000 grids, from fastest to slowest:

    • Brian: 1.08s (modified, with izip instead of zip)
    • John: 2.33s
    • DzinX: 2.36s
    • ΤΖΩΤΖΙΟΥ: 2.41s (but object initialization took 62s)
    • Eugene: 3.17s
    • Robert: 4.56s
    • Brian: 27.24s (original, with zip)

    EDIT: Added Brian's scores with izip modification and it won by a large amount!

    John's solution is also very fast, although it uses indices (I was really surprised to see this!), whereas Robert's and Brian's (with zip) are slower than the question creator's initial solution.

    So let's present Brian's winning function, as it is not shown in proper form anywhere in this thread:

    from itertools import izip
    for a_row,b_row in izip(alist, blist):
        for a_item, b_item in izip(a_row,b_row):
            if a_item.isWhatever:
                b_item.doSomething()
    

提交回复
热议问题