Alexander Clarke - 1 year ago 71

Python Question

I have a list of lists and need to find the max value in the last list and last value of each list

`score_matrix = [[6, 1, 2], [1, 2, 3], [3, 4, 5]]`

max_value, max_index = max((x, (i, j))

for i, row in enumerate(score_matrix)

for j, x in enumerate(row))

The code should find 5 as the max value however currently finds 6.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

If you only want the *last* value in each row to count, only include that in the generator expression:

```
max_value, max_index = max((row[-1], (i, len(row) - 1))
for i, row in enumerate(score_matrix))
```

`row[-1]`

takes the last value of a given row, and `len(row) - 1`

produces the index of that last element.

If you also need the last *row*, then add those elements in a separate sequence; you can use `itertools.chain()`

to combine two generators:

```
from itertools import chain
max_value, max_index = max(chain(
((row[-1], (i, len(row) - 1)) for i, row in enumerate(score_matrix)),
((c, (len(score_matrix) - 1, j)) for j, c in enumerate(score_matrix[-1]))
))
```

This does include that column in the last row twice, but for one extra value it's not worth slicing the last row for.

Demo:

```
>>> from itertools import chain
>>> score_matrix = [[6, 1, 2], [1, 2, 3], [3, 4, 5]]
>>> max(chain(
... ((row[-1], (i, len(row) - 1)) for i, row in enumerate(score_matrix)),
... ((c, (len(score_matrix) - 1, j)) for j, c in enumerate(score_matrix[-1]))
... ))
(5, (2, 2))
```

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