Absolute sort
Let‘s try some sorting. Here is an array with the specific rules.
The array (a tuple) has various numbers. You should sort it, but sort it by absolute value in ascending order. For example, the sequence (-20, -5, 10, 15) will be sorted like so: (-5, 10, 15, -20). Your function should return the sorted list or tuple.
Hints: This task can be easily solved using these functions: sorted andabs. You should try to use the key parameter for sorting.
Precondition: The numbers in the array are unique by their absolute values.
Input: An array of numbers , a tuple..
Output: The list or tuple (but not a generator) sorted by absolute values in ascending order.
题目大义:按绝对值排序
还是C语言的思路,sorted中传入cmp函数,如果x < y返回负值,x > y返回正值,x = y返回0
1 def cmp(numberA, numberB): 2 return abs(numberA) - abs(numberB) 3 4 def checkio(numbers_array): 5 return sorted(numbers_array, cmp)
不过既然用了Python如此高大上的语言,自然要显摆下,sorted还有一个参数为key,实际上sorted(number_array, key=abs)即可
Absolute sort