Reputation: 3248
I have a list of nested lists:
scoring_matrix = [[1, 2, 7], [3, 5, 2], [2, 2, 7]]
I am trying to get the max value from all last items in the nested lists, together with the index/indices of the nested list(s) with that max value. All nested lists are of equal length.
In this example:
item output (value, index)
2 [7, [0, 2]]
I also needed to get the highest value and index/indices for the last nested list, which I worked out:
max_last_list = [index for index, item in enumerate(scoring_matrix[-1]) if item == max(scoring_matrix[-1])]
I am attempting to rewrite this line to make it work on my problem, but I can't find out how to do it.
The solution cannot make use of non-built in modules
Upvotes: 0
Views: 311
Reputation: 755
Try to make your solution readable. Instead of a clever one-liner, more code with clear variable names is often easier to comprehend.
I would first calculate the maximum and in a second step find the indices for that maximum.
scoring_max = max(l[-1] for l in scoring_matrix)
indices = [i for i, sublist in enumerate(scoring_matrix) if sublist[-1] == scoring_max]
return [scoring_max, indices]
The solution to your second problem is very similar.
last_sublist = scoring_matrix[-1]
list_max = max(last_sublist)
indices = [i for i, val in enumerate(last_sublist) if val == list_max]
Upvotes: 1
Reputation: 54148
Based on my first answer, and other answers below :
Compute the end's max and find it in the sublists
# Find the max of the ends value
max_end = max(map(lambda x: x[-1], scoring_matrix))
# Find the sublist whe the last if the overall max
indexes = [index for index, item in enumerate(scoring_matrix) if item[-1] == max_end]
# Group result
result = [max_end, indexes]
print(result)
Keep the ends together and work on them
# Put all ends value in a list
ends = list(zip(*scoring_matrix))[2]
# Iterate over the ends to find the overall max
indexes = [i for i, v in enumerate(ends) if v == max(ends)]
# Group result
result = [max(ends), indexes]
print(result)
Upvotes: 4
Reputation: 24232
Keep it simple, get the max, then create the list of indices:
scoring_matrix = [[1, 2, 7], [3, 5, 2], [2, 2, 7]]
m = max(sublist[2] for sublist in scoring_matrix)
out = [m, [i for i, sub in enumerate(scoring_matrix) if sub[2] == m]]
print(out)
#[7, [0, 2]]
Upvotes: 1
Reputation: 30605
You can also try this :
maxi = max(sum(scoring_matrix,[]))
res = [maxi,[n for n,i in enumerate(scoring_matrix) if maxi in i]]
Output:
[7, [0, 2]]
Upvotes: 1
Reputation: 71570
Try using the below code:
l = list(zip(*scoring_matrix))[2]
print([max(l), [i for i, v in enumerate(l) if v == max(l)]])
Output:
[7, [0, 2]]
Upvotes: 3
Reputation: 10960
Adding to @U10-Forward's answer,
l = list(zip(*scoring_matrix))[2]
print([max(l), [i for i, v in enumerate(l) if v == max(l)]])
Upvotes: 1