高效的双循环 [英] Efficient double for loop

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

问题描述

执行双重for循环的最有效方法(或Python方式)如下所示(我知道如何执行此操作以进行列表理解,但不返回单个对象):

What is the most efficient (or Pythonic way) to carry out a double for loop as in below (I know how to do this for list comprehension but not for a single object to be returned):

for i in range(0, 9):
    for j in range(0, 9):
        if self.get(i)[j] == "1":
            return (i, j)

推荐答案

>>> next(((i, j)
           for i in range(0, 9)
           for j in range(0, 9)
           if self.get(i)[j] == "1"), None)

如果未找到任何内容,它将返回None.

This will return None if nothing is found.

请参阅 next 的文档a>.

第一个参数是生成器.如果提供None作为第二个参数,则需要此参数.否则,您可以跳过多余的括号.如果您不提供None,尽管它会抛出 StopIteration 例外,如果未找到任何内容.

The first parameter is a generator. You need this if you supply None as the second parameter. Otherwise you can skip the extra parentheses. If you don't supply None though it will throw a StopIteration exception if nothing is found.

这篇关于高效的双循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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