从网格返回坐标 [英] Returning co-ordinates from a grid

查看:59
本文介绍了从网格返回坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 6x6 网格,我试图从字符串返回网格中每个字符的坐标.

I have 6x6 grid and I am trying to return the co-ordinates of each character in the grid from a string.

我的想法是:

  1. 将字符串转换为字符列表.
  2. 通过网格枚举以检查字符是否存在.
  3. 打印所有字符的坐标??

这是我的代码(不起作用):

Here is my code(doesn't work):

grid = [
        ["A","B","C","D","E","F"],
    ["A","8","3","P","S","2","Z"],
    ["B","7","T","O","R","1","Y"],
    ["C","6","Q","N","M","0","X"],
    ["D","5","G","L","K","U","W"],
    ["E","4","9","I","H","J","V"],
    ["F","C","E","B","F","A","D"]
    ]

print("Please enter a message to encode:")
message = raw_input()

lst = list(message)

search = lst

for rownum, row in enumerate(grid):
    for colnum, value in enumerate(row):
        if value == search:
            print "(%d,%d)" % (rownum, colnum)

我想要实现的是,如果您输入hello",它将返回 ED FC DC DC BC.

What I am trying to achieve is if you inputed "hello" it would return ED FC DC DC BC.

任何帮助将不胜感激.

推荐答案

与其在整个 grid 中搜索每个字符,不如对网格进行预处理以获得位置,创建将每个字符映射到其位置的字典:

Rather than searching through the whole grid for each character, you would be better pre-processing your grid to get the locations, creating a dictionary mapping each character to its location:

locations = {}
for x in range(1, len(grid)): # note offset for label row
    for y in range(1, len(grid[x])-1): # and label column
        locations[grid[x][y]] = (grid[0][y-1], grid[x][0])

注意最后一行的grid[0][y-1];列表中的第一行比其他行短.或者,您可以使用 None 或空字符串 "" 填充它并删除 -1:

Note the grid[0][y-1] in the last line; the first row in your list is shorter than the others. Alternatively, you could pad it with None or an empty string "" and remove the -1:

grid = [[None, "A", "B", ...], ...]

这将创建一个格式为 {character: (column, row)}:

This creates a dictionary in the form {character: (column, row)}:

 locations == {'P': ('C', 'A'), 'Q': ('B', 'C'), ...}

然后就可以轻松获取行和列了:

Then you can easily get the row and column:

for c in lst:
    col, row = locations[c]

值得注意的是,您需要将输入的字符转换为大写,否则您会得到一个KeyError(因为小写字符不在您的网格中):

It is worth noting that you need to convert the characters input into upper case, otherwise you will get a KeyError (as lower-case characters aren't in your grid):

lst = list(raw_input("Please enter a message to encode: ").upper())

这篇关于从网格返回坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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