I have this code where I have an array of sizes (i,j) and for each of the j variables, I want to select the highest out of the I variables.
For example, I have array [[2,5,1][12,4,6],[1,7,8],[2,4,5]] and I want to get the highest number out of each of the inner arrays so it should return: [5,12,8,5]
I have the following code which works fine, however, it's a bit messy and hard to read so my question is can I make it more compact?
Here is the code I have:
high_net_profit = list()
for i in range(len(self.accum_profit[0])):
high_value = 0
for j in range((len(self.accum_profit))):
if j == 0:
high_value = self.accum_profit[j][i]
else:
if self.accum_profit[j][i] > high_value: high_value = self.accum_profit[j][i]
high_net_profit.append(high_value)
Try:
lst = [[2, 5, 1], [12, 4, 6], [1, 7, 8], [2, 4, 5]]
out = [max(l) for l in lst]
print(out)
Prints:
[5, 12, 8, 5]
Or:
out = [*map(max, lst)]
print(out)