Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

python - Sorting by absolute value without changing to absolute value

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(numbers_array, key = abs(numbers_array))


sorting((-20, -5, 10, 15))

According to the python wiki (https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions), the sorted(list, key=) function is suppose to sort with the parameter key without actually altering the elements of the list. However, abs() only takes int() and I haven't worked out a way to make that tuple into an int, if that's what I need to do.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...