简体   繁体   English

替代Python中的循环嵌套

[英]Alternative to nesting for loops in Python

I've read that one of the key beliefs of Python is that flat > nested. 我已经读过Python的一个关键信念是flat>嵌套。 However, if I have several variables counting up, what is the alternative to multiple for loops? 但是,如果我有几个变量计数,多个for循环的替代方法是什么? My code is for counting grid sums and goes as follows: 我的代码用于计算网格总和,如下所示:

def horizontal():
    for x in range(20):
        for y in range(17):
            temp = grid[x][y: y + 4]
            sum = 0
            for n in temp:
                sum += int(n)
            print sum # EDIT: the return instead of print was a mistype

This seems to me like it is too heavily nested. 在我看来,它似乎太嵌套了。 Firstly, what is considered to many nested loops in Python ( I have certainly seen 2 nested loops before). 首先,考虑到Python中的许多嵌套循环(我之前已经看过2个嵌套循环)。 Secondly, if this is too heavily nested, what is an alternative way to write this code? 其次,如果嵌套太多,编写此代码的另一种方法是什么?

from itertools import product

def horizontal():
    for x, y in product(range(20), range(17)):
        print 1 + sum(int(n) for n in grid[x][y: y + 4])

You should be using the sum function. 你应该使用sum函数。 Of course you can't if you shadow it with a variable, so I changed it to my_sum 当然,如果你用变量来遮蔽它,你就不能,所以我把它改成了my_sum

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. 以上输出13260,用于在第一行代码中创建的特定网格。 It uses sum() three times. 它使用sum()三次。 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. 最里面的总和将grid[x][y: y + 4]的数字相加,加上问题代码中显示的稍微奇怪的初始值sum = 1 The middle sum adds up those values for the 17 possible y values. 中间总和将17个可能的y值相加。 The outer sum adds up the middle values over possible x values. 外部总和将中间值与可能的x值相加。

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]

You can use a dictionary to optimize performance significantly 您可以使用字典来显着优化性能

This is another example: 这是另一个例子:

locations = {}
for i in range(len(airports)):
    locations[airports["abb"][i][1:-1]] = (airports["height"][i], airports["width"][i])

for i in range(len(uniqueData)):
    h, w = locations[uniqueData["dept_apt"][i]]
    uniqueData["dept_apt_height"][i] = h
    uniqueData["dept_apt_width"][i] = w

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM