如何计算python中数组的绝对值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18777737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to calculate the absolute value for an array in python?
提问by wesley
How to calculate the absolute value for an array in python?
如何计算python中数组的绝对值?
for example: a = [5,-2,-6,5]
例如:a = [5,-2,-6,5]
I want to know the max of abs(a), and the answer should be 6. Thank you!
我想知道abs(a)的最大值,答案应该是6,谢谢!
采纳答案by Anorov
max(abs(i) for i in [5, -2, -6, 5])
max(abs(i) for i in [5, -2, -6, 5])
回答by SethMMorton
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
函数可以接受一个可迭代对象,并且abs(x) for x in a
是一个生成器,它将给出 中每个元素的绝对值a
。
回答by Phil Hunt
Alternately you could use:
或者,您可以使用:
max(map(abs, [5,-2,-6,5]))
回答by Kiattisak Anoochitarom
max(abs(i) for i in [5, -2, -6, 5])
The List Comprehensive Solution :)
列表综合解决方案:)
回答by Wuzhou Zhang
Try this:
尝试这个:
import numpy
max(numpy.absolute(a))