Hal Lawrence - 1 year ago 72
Python Question

# Functions: Returning strings and tuples of lists?

Working these functions and I'm having trouble returning the lists of strings to tuples and indexes. First one I'm trying to return every first occurrence of the letter strings with its index location, but so far I'm only able to return a single string with its index, how can I make it so it iterates through each list and chooses the earliest occurrence of the string?

``````area3 = [['.', '.', '.', 'a'],
['.', 'B', '.', 'a'],
['.', '.', '.', '.'],
['.', 'Y', 'Y', 'Y'],
['.', '.', '.', '.'],
['.', 'x', '.', '.']]
def zone_lists(area):
for row in area:
for letter in row:
if ('A' <= letter <= 'Z' or 'a' <= letter <= 'z'):
return letter, area.index(row), row.index(letter)
zone_lists(area3) # Should return [('a', 0, 3), ('B', 1, 0), ('Y', 3, 1), ('x', 5, 1)]
``````

In this function, it should return the later string value of 'e', but I'm getting a value error. I'm not sure if the recursive call is correct, is there a way call it without using built in functions like enumerate?

``````def last_list_val(value,area):
for row in area:
for letter in row:
if value == letter:
return area.index(row[0:-1]), row.index(letter[0:-1]) #Backward call?
last_list_val('Y',area3) #Should return (3,3)
``````

The first function:

``````area3 = [['.', '.', '.', 'a'],
['.', 'B', '.', 'a'],
['.', '.', '.', '.'],
['.', 'Y', 'Y', 'Y'],
['.', '.', '.', '.'],
['.', 'x', '.', '.']]
def zone_lists(area):
result = []
for i, row in enumerate(area):
for j, letter in enumerate(row):
if letter.isalpha():
result.append((letter, i, j))
break  # remove this line if you want to have both 'B' and 'a' from row 1
return result

zone_lists(area3) # Should return [('a', 0, 3), ('B', 1, 0), ('Y', 3, 1), ('x', 5, 1)]
``````

The second:

``````def last_list_val(value, area):
for i in range(len(area) - 1, -1, -1):
row = area[i]
for j in range(len(row) - 1, -1, -1):
letter = row[j]
if value == letter:
return i, j
``````

I used `enumerate` here in the first function. But if you don't like it (or some reason can not use it), you can always use the old fashion `for i in range(len(area)):` to get the indice and use `area[i]` to get the corresponding values, like I did in the second function (slightly different because I did them reversely).

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