How to search nested list grid and give lettered coordinates in Python? [closed]

拥有回忆 提交于 2019-12-02 04:57:54

You can use Python's enumerate to iterate over values and provide an index position of each value as you go:

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)

You can adapt this into your chosen function structure, such as the following (if values in your grid are unique):

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")

As this will raise a ValueError if the value isn't found, you'll have to handle this in your calling code.

If you then need to map between 0-indexed row and column numbers to the letters A...F you can do something like:

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

Which will give you the following:

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

Putting it all together gives you:

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

I realise you're doing this for learning/homework purposes, but I'll point this out for something for you to bear in mind later. It's easier to think of what you have as something of 36-items (that just happens to be representable as a 6x6) - or more explicity - you have a character -> coord, and a dict is very useful to do this, and reverse it...

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()}
asheeshr

This is a simple way to get the co-ordinates of a character in the grid :

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!