如何搜索嵌套列表网格并在Python中给出字母坐标?

时间:2013-01-05 13:29:35

标签: python list matrix grid nested

我是python的新手,为了实现这一目标而努力奋斗。 这是我的任务:

  

Six-Letter Cipher是一种编码秘密消息的方法   涉及替代和转置。加密开始于   用A到Z的字母随机填充66网格   和0到9之间的数字(总共36个符号)。这个网格必须是   消息的发送者和接收者都知道。行和   网格的列标有字母A,B,C,D,E,F。

     

编写一个实现六字母密码方法的Python程序。   你的程序应该:   1.创建一个6x6网格,并按照第一段中的描述随机填写字母和数字,然后提示用户输入   秘密消息。   2.用户输入密码消息后,显示6x6网格和生成的密文。   3.提示用户输入密文以显示原始消息。可以要求用户将每两个字母分开   带空格或逗号的密文。

我正在努力解决的问题是如何在嵌套列表中搜索已输入的随机放置的字母并给出坐标。坐标也不是以数字表示,即0,1,而不是字母,即A,B 我想我可以管理编码和解码,一旦我有了如何使用这个嵌套列表的想法。

到目前为止,这是我的代码:

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

def main():
    print("Welcome to the sixth cipher")
    print("Would you like to (E)Encode or (D)Decode a message?")
    operation = input()

    if(operation == "E"):
        encodecipher()
    elif(operation == "D"):
        decodecipher()
    else:
        print("Sorry, input not recognised")

def encodecipher():
    print("Please enter a message to encode:")
    messagetoencode = input()



def decodecipher():
    print("Decode Test")
    rowcolumn()


def rowcolumn():
    pass

main()

3 个答案:

答案 0 :(得分:4)

我意识到你是为了学习/家庭作业而做这件事,但是我会指出这件事是为了你以后要记住的事情。你可以更容易地想到你拥有的东西是36件物品(恰好可以表示为6x6) - 或者更明确 - 你有一个角色 - > coord和dict非常有用,可以反转它......

from string import ascii_uppercase, digits
from random import shuffle
from itertools import product

# build 36 items list and randomise it
chars = list(ascii_uppercase + digits)
shuffle(chars)

# alternatively, use your existing grid:
from itertools import chain
chars = list(chain.from_iterable(grid))
# ...


# Create char -> (coords)
lookup = dict(zip(chars, product('ABCDEF', repeat=2)))
# Swap over so (coords) -> char
rev_lookup = {v: k for k,v in lookup.iteritems()}

答案 1 :(得分:2)

您可以使用Python的枚举来迭代值并提供每个值的索引位置:

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

search = 'D'

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

您可以将其调整为您选择的功能结构,例如以下内容(如果网格中的值是唯一的):

def findvalue(grid, value):
    for rownum, row in enumerate(grid):
        for colnum, itemvalue in enumerate(row):
            if itemvalue == value:
                return (rownum, colnum)
    raise ValueError("Value not found in grid")

如果找不到值,这将引发ValueError,您必须在调用代码中处理此问题。

如果您需要在0索引的行号和列号之间映射到字母A ... F,您可以执行以下操作:

def numbertoletter(number):
    if number >= 0 and number <= 26:
        return chr(65 + number)
    else:
        raise ValueError('Number out of range')

这将为您提供以下内容:

>>> numbertoletter(0)
'A'
>>> numbertoletter(1)
'B'

把它们放在一起就可以了:

value = 'B'
row, col = map(numbertoletter, findvalue(grid, value))
print "Value '%s' found at location (%s, %s)" % (value, row, col)

答案 2 :(得分:1)

这是获取网格中角色坐标的简单方法:

def find_pos(s):
    for i, j in enumerate(grid):
        try:
            return i, j.index(s)
        except ValueError:
            continue
    raise ValueError("The value {0!r} was not found.".format(s))


>>> find_pos("O")
(2, 3)