[英]Pythonic way to find maximum absolute value of list
The following list is given: 给出以下列表:
lst = [3, 7, -10]
I want to find the maximum value of absolute value. 我想找到绝对值的最大值。 For the above list it will be 10 (abs(-10) = 10).
对于上面的列表,它将是10(abs(-10)= 10)。
I can do it as follows: 我可以这样做,如下所示:
max_abs_value = lst[0]
for num in lst:
if abs(num) > max_abs_value:
max_abs_value = abs(num)
What are better ways of solving this problem? 解决此问题的更好方法是什么?
The built-in max
takes a key function, you can pass that as abs
: 内置的
max
具有一个关键功能,您可以将其作为abs
传递:
>>> max([3, 7, -10], key=abs)
-10
You can call abs
again on the result to normalise the result: 您可以再次对结果调用
abs
以将结果标准化:
>>> abs(max([3, 7, -10], key=abs))
10
Use map
, and just pass abs
as your function, then call max on that: 使用
map
,只需将abs
作为函数传递,然后在其上调用max:
>>> max(map(abs, [3, 7, -10]))
10
max(max(a),-min(a))
It's the fastest for now, since no intermediate list is created (for 100 000 values): 这是目前最快的,因为没有创建中间列表(针对100 000个值):
In [200]: %timeit max(max(a),-min(a))
100 loops, best of 3: 8.82 ms per loop
In [201]: %timeit abs(max(a,key=abs))
100 loops, best of 3: 13.8 ms per loop
In [202]: %timeit max(map(abs,a))
100 loops, best of 3: 13.2 ms per loop
In [203]: %timeit max(abs(n) for n in a)
10 loops, best of 3: 19.9 ms per loop
In [204]: %timeit np.abs(a).max()
100 loops, best of 3: 11.4 ms per loop
You can use max()
with a generator comprehension: 您可以将
max()
与生成器理解一起使用:
>>> max(abs(n) for n in [3, 7, -10])
10
>>>
ProTip: Try to avoid naming your variables after builtin names such as list
. ProTip:尽量避免在内置名称(例如
list
之后命名变量。 Rename to something else like lst
or L
. 重命名为
lst
或L
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.