简体   繁体   English

Python:尝试创建一个两变量上下文管理器

[英]Python: trying to create a two variable context manager

I'm new to Python so my guess I'm doing something "syntactically" incorrect.我是 Python 新手,所以我猜我在做一些“语法上”不正确的事情。 I'm trying to iterate over a grid using row and col as a coordinate system.我正在尝试使用rowcol作为坐标系遍历网格。 This my code so far:到目前为止,这是我的代码:

from contextlib import contextmanager

# this is the behavior I want
for row in range(10):
    for col in range(10):
        print("row: {}, col: {}".format(row, col))

@contextmanager
def grid_iter():
    for row in range(10):
        for col in range(10):
            yield row, col

# this is my attempt at a context manager so I can reuse this.
with grid_iter() as row, col:
    print("row: {}, col: {}".format(row, col))

This is the output I'm getting:这是我得到的输出:

row: 0, col: 0
row: 0, col: 1
row: 0, col: 2
....
row: 9, col: 7
row: 9, col: 8
row: 9, col: 9
Traceback (most recent call last):
  File "grid_iterator.py", line 17, in <module>
    with grid_iter() as row, col:
AttributeError: __exit__

you should be able to just do:你应该能够做到:

def grid_iter():
    for row in range(10):
        for col in range(10):
            yield row, col

for row, col in grid_iter():
    print("row: {}, col: {}".format(row, col))

the usage of yield itself makes grid_iter return a generator (you can check this by running print(type(grid_iter())) and then you use it like a normal for-in loop yield本身的使用使grid_iter返回一个生成器(你可以通过运行print(type(grid_iter()))来检查它,然后你可以像普通的 for-in 循环一样使用它

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

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