Reputation: 1693
Im not entirely sure what the name of this type of data structure (a table??),
T = [[(0, ''), (-1, '<'), (-2, '<')], [(-1, '^'), (1, '\\'), (0, '\\')], [(-2, '^'), (5, '^'), (0, '\\')]]
Anyway, we're using it in college for a certain type of program, but that doesn't really matter, basically I have a very complex program already done which use's this type of data structure, however now I need to write another program that does something very similar, basically it would save me a great deal of work if there was a way to get the maximum number from this list of tuples, in a list of lists, along with the index of that value. Also the number of tuples, or lists is not fixed, that will change depending on the length of a string put into the program. It also important to note I am not just looking for the maximum number, but also the index of that number. With this type of data structure,
T[2][2][1]
would return
'\ \'
In the example I gave above I would be looking for
T[2][1][0]
which would return
5
Any help is greatly appreciated :)
Upvotes: 1
Views: 152
Reputation: 65851
Good old way?
def find_max(table):
max_val = table[0][0][0] # something to start with
max_index = (0, 0)
for l in table:
for t in l:
if t[0] > max_val:
max_val = t[0]
max_index = (table.index(l), l.index(t))
return (max_val, max_index)
Upvotes: 0
Reputation: 12960
T=[[(0, ''), (-1, '<'), (-2, '<')], [(-1, '^'), (1, '\\'), (0, '\\')], [(-2, '^'), (5, '^'), (0, '\\')]]
m, ma, mb=None, 0, 0
for a in xrange(len(T)):
for b in xrange(len(T[a])):
if m is None or T[a][b] > m:
m, ma, mb=T[a][b], a, b
print m, ma, mb
This will print
(5, '^') 2 1
Upvotes: -1
Reputation: 208665
Here is a pretty concise method:
max((k, (i, j)) for i, lst in enumerate(T) for j, (k, _) in enumerate(lst))
For your sample data:
>>> T = [[(0, ''), (-1, '<'), (-2, '<')], [(-1, '^'), (1, '\\'), (0, '\\')], [(-2, '^'), (5, '^'), (0, '\\')]]
>>> max((k, (i, j)) for i, lst in enumerate(T) for j, (k, _) in enumerate(lst))
(5, (2, 1))
>>> T[2][1]
(5, '^')
Upvotes: 2
Reputation: 69248
Homework, eh? Here's some clues:
iterate through the list, and the list, and compare the 0th values
enumerate is you friend
Not homework? OKay, here's a solution :)
high = 0
index = None
for i, lst in enumerate(T):
for j, tpl in enumerate(lst):
current = T[i][j][0]
if current > high:
index = i, j, 0
high = max(high, current)
print index
Upvotes: 0