[英]How to find the highest magnitude int in a Python list?
如果列表有正整数和负整数,我如何找到列表中具有最大量级的项目的值?
Late reply, but the other answer and the linked duplicate question seems to have missed an important aspect of your question, namely that you want the value , not the absolute value , with the largest magnitude.迟到的答复,但另一个答案和链接的重复问题似乎错过了您问题的一个重要方面,即您想要的是具有最大量级的值,而不是绝对值。 In other words, in a list like [-10, 0, 5]
, you want the result to be -10
, not 10
.换句话说,在像[-10, 0, 5]
这样的列表中,您希望结果是-10
,而不是10
。
To get the value with its original sign, you could (conceptually) follow these steps:要获得具有原始符号的值,您可以(从概念上)按照以下步骤操作:
This can be done quite easily in numpy by using argmax
, which returns the index of the maximum value from an array.这可以在 numpy 中通过使用argmax
很容易地完成,它返回数组中最大值的索引。 Step-by-step, it would look like this:一步一步,它看起来像这样:
# 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
This can be done in a single line like so:这可以在一行中完成,如下所示:
x = xs[np.argmax(np.abs(xs))]
If you mean highest magnitude regardless of negative or positive sign, then you would take the maximum of the list resulting from taking the absolute value of each constituent list value.如果无论负号还是正号,您都表示最高幅度,那么您将取列表中的最大值,该列表取每个组成列表值的绝对值。 Does that make sense?这有意义吗?
Here is an example:
numbers = [3, 5, 7, -18]
matrix=[]
for x in numbers:
matrix.append(abs(x))
max(matrix)
this will find the largest value in the list and convert it to positive (afterwards).这将找到列表中的最大值并将其转换为正数(之后)。 Useful for normalizations abs(max(xs,key=abs))对归一化有用 abs(max(xs,key=abs))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.