Efficient double for loop

夙愿已清 提交于 2019-12-08 07:44:48

问题


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)

回答1:


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

This will return None if nothing is found.

See the documentation for next.

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.



来源:https://stackoverflow.com/questions/32976373/efficient-double-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!