如何在python列表中计算最高幅度int?

时间:2017-07-24 16:43:04

标签: python max

如果列表具有正整数和负整数。如何找到最大幅度的?

3 个答案:

答案 0 :(得分:1)

如果您的意思是无论负号或正号都表示最高幅度,那么您将获取每个成分列表值的绝对值所得到的最大值。这有意义吗?

Here is an example:
numbers = [3, 5, 7, -18]

matrix=[]
for x in numbers:
    matrix.append(abs(x))
max(matrix)

答案 1 :(得分:0)

最新答复,但另一个答案和链接的重复问题似乎错过了您问题的重要方面,即您想要的是,而不是绝对值,幅度最大。换句话说,在类似[-10, 0, 5]的列表中,您希望结果为-10,而不是10

要获取具有原始符号的值,可以(从概念上)遵循以下步骤:

  1. 获取列表的副本,其中所有值均转换为它们的绝对值
  2. 找到具有最大绝对值的值的 index
  3. 返回该索引处的

使用argmax可以很容易地在numpy中完成,它从数组中返回最大值的索引。逐步,它看起来像这样:

# Create a numpy array from the list you're searching:
xs = np.array([-10, 0, 5])

# Get an array where each value is converted to its absolute value:
xs_abs = np.abs(xs) 
# This gives [10, 0, 5]

# Get the index of the highest absolute value:
max_index = np.argmax(xs_abs) 
# This gives 0

# Get the number from the original array at the max index:
x = xs[max_index] 
# This gives -10

这可以像这样在一行中完成:

x = xs[np.argmax(np.abs(xs))]

答案 2 :(得分:0)

这将在列表中找到最大值,然后将其转换为正值。对规范化很有用 abs(max(xs,key = abs))