Pythonic shortcut for doubly nested for loops?

前端 未结 5 793
再見小時候
再見小時候 2021-02-12 16:28

Consider if I had a function that took a tuple argument (x,y), where x was in the range(X), and y in the range(Y), the normal way of doing it would be:

for x in          


        
5条回答
  •  粉色の甜心
    2021-02-12 17:24

    from itertools import product
    
    def something_like_range(*sizes):
        return product(*[range(size) for size in sizes])
    

    for a usage close to what you wanted:

    for x,y in something_like_range(X,Y):
        your_function(x,y)
    

    =)

提交回复
热议问题