Sorting by absolute value without changing to absolute value

后端 未结 3 421
滥情空心
滥情空心 2020-12-06 12:07

I want to sort a tuple using abs() without actually changing the elements of the tuple to positive values.

def sorting(numbers_array):
    return sorted(numb         


        
相关标签:
3条回答
  • 2020-12-06 12:24

    So if you want to sort these 4 values (-20, -5, 10, 15) the desired output would be: [-5, 10, 15, -20], because you are taking the absolute value.

    So here is the solution:

    def sorting(numbers_array):
        return sorted(numbers_array, key = abs)
    
    
    print(sorting((-20, -5, 10, 15)))
    
    0 讨论(0)
  • 2020-12-06 12:37

    You need to give key a callable, a function or similar to call; it'll be called for each element in the sequence being sorted. abs can be that callable:

    sorted(numbers_array, key=abs)
    

    You instead passed in the result of the abs() call, which indeed doesn't work with a whole list.

    Demo:

    >>> def sorting(numbers_array):
    ...     return sorted(numbers_array, key=abs)
    ... 
    >>> sorting((-20, -5, 10, 15))
    [-5, 10, 15, -20]
    
    0 讨论(0)
  • 2020-12-06 12:46
    lst = [-1, 1, -2, 20, -30, 10]
    >>>print(sorted(lst, key=abs))
    >>>[-1, 1, -2, 10, 20, -30]
    
    0 讨论(0)
提交回复
热议问题