n00bprogrammer22 n00bprogrammer22 - 1 year ago 78
Python Question

Create a list of lists of tuples where each tuple is the first occurrence of a letter along with its row and column in the list of lists

I need to write a function that creates a list of tuples of the first occurrence of a letter followed by its row and column in a list of lists.

Example Input and Output:


lot2 = [['.','M','M','H','H'],

#Output: [('M', 0, 1), ('H', 0, 3), ('f', 1, 4), ('B', 2, 0)]

As you can see the function should only look for the first occurrence of a letter and not all occurrences. Thanks for any help.


letter = '.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
def list_cars(lst):
for y, row in enumerate(lst):
if letter in row:
return letter, y, row.index(letter)

Answer Source

First off, use the string library to get a string of all upper and lower case letters:

import string
Out[40]: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

collector = []
output_list = []
for i in lot2:
    for j in i:
        if j in string.ascii_letters and j not in collector:
            tmp = (j,lot2.index(i), i.index(j))

output_list should give you what you want.

edit: If you want to also capture full-stops use string.printable - although this will give you a string that consists of additional punctuation and white space characters as well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download