Alternative to nesting for loops in Python

后端 未结 3 1765
小蘑菇
小蘑菇 2020-12-18 10:22

I\'ve read that one of the key beliefs of Python is that flat > nested. However, if I have several variables counting up, what is the alternative to multiple for loops? My c

3条回答
  •  被撕碎了的回忆
    2020-12-18 10:53

    grid = [range(20) for i in range(20)]
    sum(sum( 1 + sum(grid[x][y: y + 4]) for y in range(17)) for x in range(20))
    

    The above outputs 13260, for the particular grid created in the first line of code. It uses sum() three times. The innermost sum adds up the numbers in grid[x][y: y + 4], plus the slightly strange initial value sum = 1 shown in the code in the question. The middle sum adds up those values for the 17 possible y values. The outer sum adds up the middle values over possible x values.

    If elements of grid are strings instead of numbers, replace
    sum(grid[x][y: y + 4])
    with
    sum(int(n) for n in grid[x][y: y + 4]

提交回复
热议问题