如何计算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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:49:01  来源:igfitidea点击:

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

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 maxfunction can accept an iterable, and abs(x) for x in ais 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))