[英]How to search through a 2d list and prints the location (x, y)
I have this problem in my python class.我的 python class 有这个问题。 I have to loop through a 2d list of items and print what is found and in what location (x, y).我必须遍历一个二维项目列表并打印找到的内容和位置(x,y)。
Output that I should get:我应该得到的 Output:
In square (1, 0) we found apple
In square (4, 0) we found lion
In square (1, 1) we found kobra
In square (2, 1) we found cat
In square (3, 1) we found kobra
In square (0, 2) we found hyena
In square (2, 2) we found apple
In square (3, 2) we found kobra
The code I have so far:我到目前为止的代码:
ITEMS = {
"a": "apple",
"k": "kobra",
"@": "cat",
"h": "hyena",
"l": "lion"
}
def inspect_square(square, y, x):
while True:
if square == "a":
print("In square ({}, {}) we found {}".format(x, y, ITEMS[square]))
elif square == "k":
print("In square ({}, {}) we found {}".format(x, y, ITEMS[square]))
elif square == "@":
print("In square ({}, {}) we found {}".format(x, y, ITEMS[square]))
elif square == "h":
print("In square ({}, {}) we found {}".format(x, y, ITEMS[square]))
elif square == "l":
print("In square ({}, {}) we found {}".format(x, y, ITEMS[square]))
else:
continue
def search_field(field):
for y in field:
for x in y:
inspect_square(square, y, x)
field = [
[" ", "a", " ", " ", "l"],
[" ", "k", "@", "k", " "],
["h", " ", "a", "k", " "]
]
search_field(field)
I get error message that square is not defined but I'm not sure if that's the main problem in my work so far.我收到未定义正方形的错误消息,但我不确定这是否是我目前工作中的主要问题。 It might be a simple fix, but I can't see it.这可能是一个简单的修复,但我看不到它。 How can I continue?我该如何继续? Is there a mistake?有错误吗?
Thanks in advance!提前致谢!
Added traceback:添加回溯:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\Downloads\pelto.py in <module>
36
37
---> 38 search_field(field)
~\Downloads\pelto.py in search_field(field)
25 for y in field:
26 for x in y:
---> 27 inspect_square(square, y, x)
28
29
NameError: name 'square' is not defined
You get the error when calling the inspect_square
.调用inspect_square
时出现错误。 Because you call it with square
which is not defined.因为你用未定义的square
调用它。
Another solution另一种解决方案
for y, line in enumerate(field):
for x, item in enumerate(line):
if item != " ":
print("In square ({}, {}) we found {}".format(x, y, ITEMS[item]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.