简体   繁体   中英

How to calculate the absolute value for an array in python?

How to calculate the absolute value for an array in python?

for example: a = [5,-2,-6,5]

I want to know the max of abs(a), and the answer should be 6. Thank you!

max(abs(i) for i in [5, -2, -6, 5])

Try this:

import numpy
max(numpy.absolute(a))

Try this

a = [5, -2, -6, 5]
print max(abs(x) for x in a)

The max function can accept an iterable, and abs(x) for x in a is a generator which will give the absolute value of each element in a .

或者你可以使用:

max(map(abs, [5,-2,-6,5]))
max(abs(i) for i in [5, -2, -6, 5])

列表综合解决方案:)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM