如何使用python使选择最高数字更加紧凑



我有一段代码,其中我有一个大小为(I,j(的数组,对于每个j个变量,我想从I个变量中选择最高的。

例如,我有一个数组[[2,5,1][12,4,6],[1,7,8],[2,4,5]],我想从每个内部数组中得到最高的数字,所以它应该返回:[5,12,8,5]

我有下面的代码,它工作得很好,但是,它有点乱,很难阅读,所以我的问题是我能让它更紧凑吗?

这是我的代码:

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)

尝试:

lst = [[2, 5, 1], [12, 4, 6], [1, 7, 8], [2, 4, 5]]
out = [max(l) for l in lst]
print(out)

打印:

[5, 12, 8, 5]

或者:

out = [*map(max, lst)]
print(out)
s =  [[2,5,1][12,4,6],[1,7,8],[2,4,5]]

如果您只需要可迭代对象:

x = map(max, s)

如果你需要一个列表,那么包装成list:

x = list(map(max, s))

这里有一个使用numpy的简单解决方案。Numpy在处理数字时是一个非常有用的库:

import numpy as np
l_in = [[2, 5, 1], [12, 4, 6], [1, 7, 8], [2, 4, 5]]
# out = [max(l) for l in l_in]  # can also be used
out = list(np.max(l_in, axis=1))
print(out)

输出:

[5, 12, 8, 5]

最新更新