Reputation: 111
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)
Upvotes: 0
Views: 70
Reputation: 103814
This makes a nice generator.
Consider:
from string import ascii_letters
def zone_list(area):
for i, sl in enumerate(area):
t=next(((j,e) for j,e in enumerate(sl) if e in ascii_letters), None)
if t:
yield (t[1], i, t[0])
Then test that:
>>> list(zone_list(area3))
[('a', 0, 3), ('B', 1, 1), ('Y', 3, 1), ('x', 5, 1)]
The second function then becomes:
def last_list_val(value,area):
for i, sl in enumerate(area):
seq=[(j,e) for j,e in enumerate(sl) if e==value]
if len(seq)>1:
yield (i, seq[-1][0])
And then:
>>> list(last_list_val('Y', area3))
[(3, 3)]
Upvotes: 1
Reputation: 6438
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).
Upvotes: 2