简体   繁体   English

查找列表中的最大绝对值

[英]Find the maximum absolute value in a list

I'm looking to get the maximum absolute value in a random list.我正在寻找随机列表中的最大绝对值。 I need to create it in a function.我需要在 function 中创建它。 I'm not sure what I'm doing wrong here.我不确定我在这里做错了什么。 I have a for loop setup so it should check each number but it's only returning the first value.我有一个 for 循环设置,所以它应该检查每个数字,但它只返回第一个值。

def main():
    print(maxabsinlst([-19, -3, 20, -1, 5, -25]))

def maxabsinlst(num):
    for x in (num):
        max_abs_value = num[5]
        if abs(x) > max_abs_value:
            max_abs_value = abs(x)
            return max(abs(max_abs_value))

main()

The shortest way would be:最短的方法是:

def maxabsinlst(num):
    return max(map(abs, num))

The map() function applies abs() to each number on the list, and returns a list of these absolute values, then max() finds the maximum in the list. map() function 将abs()应用于列表中的每个数字,并返回这些绝对值的列表,然后max()找到列表中的最大值。

You are assigning max_abs_value to num[5] inside the loop.您正在将max_abs_value分配给循环内的num[5] Instead assign it as first element of list then loop through it comparing with other elements而是将其分配为列表的第一个元素,然后循环遍历它与其他元素进行比较

def main():
    print(maxabsinlst([-19, -3, 20, -1, 5, -25]))

def maxabsinlst(num):
    max_abs_value = abs(num[0])
    for x in num[1:]:
        if abs(x) > max_abs_value:
            max_abs_value = abs(x)
    return max_abs_value

main()

OR或者

In [36]: max(abs(i) for i in [-19, -3, 20, -1, 5, -25])
Out[36]: 25

You can make this quite a bit more concise:你可以让它更简洁一些:

def max_abs_in_lst(num):
    num = [abs(i) for i in num]
    return max(num)

max_abs_value = num[5]

Every time the for loop runs, it is setting the max value to -25.每次 for 循环运行时,都会将最大值设置为 -25。 Store the value outside the for loop and initialize it with max_abs_value = 0将值存储在 for 循环之外并使用max_abs_value = 0对其进行初始化

There are a few issues with your function.您的 function 存在一些问题。 First, you're setting max_abs_value at every iteration of the for loop.首先,您在for循环的每次迭代中设置max_abs_value Second, you're assuming that the list passed to the function will have length 6 every time.其次,您假设传递给 function 的列表每次的长度都是 6。 Third, you never computed the absolute value of num[5] .第三,您从未计算过num[5]的绝对值。 So, you're comparing abs(x) to a negative number.因此,您将abs(x)与负数进行比较。 Fourth, you're returning from the function as soon as you find any value greater than max_abs_value .第四,一旦发现任何大于max_abs_value的值,您就会从 function 返回。 You have no guarantee that it was the the greatest value in the list.您无法保证它是列表中的最大值。

What you want is你想要的是

def maxabsinlist(num):
    max_abs_value=abs(num[0])
    for x in num[1:]:
        value=abs(x)
        if value > max_abs_value:
            max_abs_value=value
    return max_abs_value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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