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).
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([3, 7, -10], key=abs)
-10
You can call abs
again on the result to normalise the result:
>>> abs(max([3, 7, -10], key=abs))
10
Use map
, and just pass abs
as your function, then call max on that:
>>> 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):
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(abs(n) for n in [3, 7, -10])
10
>>>
ProTip: Try to avoid naming your variables after builtin names such as list
. Rename to something else like lst
or L
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.