0

我需要扫描几个字符串的列表(每一行都是字符串),找到符号“+”或“@”(只能出现其中一个),然后打印 x,y 坐标。左角是(0,0),如果你保持向右和向下,值会增加。

我不明白我的代码有什么问题:

    x,y=-1,-1
    for row in my_list:  
            y+=1
            for symbol in row:
                    x+=1
                    if symbol=="@":
                            makom=(x,y)
                            player="@"       
                    if symbol=="+":
                            makom=(x,y)
                            player="+"


     print makom 

列表:

####
# .#
#  ###
#*@  #
#  $ #
#  ###
####

输出:

(2,3)
4

1 回答 1

2

x您在更改行时忘记重置:

y = -1
for row in my_list:  
        x = -1
        y += 1
        for symbol in row:
                x += 1
                if symbol == "@":
                        makom = (x,y)
                        player = "@"       
                if symbol == "+":
                        makom = (x,y)
                        player = "+"


print makom

 

enumerate为了完整起见,如果您使用:D ,您就不会犯这个错误

for y, row in enumerate(my_list):
        for x, symbol in enumerate(row):
                if symbol == "@":
                        makom = (x, y)
                        player = "@"       
                if symbol == "+":
                        makom = (x, y)
                        player = "+"


print makom
于 2012-12-26T20:39:00.230 回答