替代在Python中嵌套循环 [英] Alternative to nesting for loops in Python

查看:119
本文介绍了替代在Python中嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读过,Python的一个关键信念就是flat> nested。但是,如果我有几个变量计数,什么是多个循环的替代?
我的代码是用于计算网格总和,如下所示:

  def horizo​​ntal():
for x在范围内(20):
在范围内(17):
temp = grid [x] [y:y + 4]
sum = 0
for n in temp:
sum + = int(n)
print sum#编辑:返回而不是打印错误

这在我看来好像太嵌套了。首先,Python中的许多嵌套循环被认为是什么(我之前肯定见过2个嵌套循环)。其次,如果嵌套太重,那么编写这个代码的另一种方法是什么?

解决方案

  b 



$ b $($)

$ (int(n)for grid [x] [y:y + 4])

应该使用 sum 函数。当然,如果你用一个变量来映射它,所以我改变它为 my_sum


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 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). 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. Of course you can't if you shadow it with a variable, so I changed it to my_sum

这篇关于替代在Python中嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆