I want to sort this list a = [31415926535897932384626433832795, 1, 3, 10, 3, 5]. To reduce time complexity I want to first check whether the 2 elements are of same length or not. If both are of not same length I will swap them according to their length otherwise I will check which number is bigger and swap them. I want to implement this using .sort()
function which have a parameter called key
. I can use a.sort(key=len)
but it will only work for the test cases with different length inputs. Please help me regarding this.
When you are using sort()
in Python, you can provide a function or anonymous ( lambda
) function to it as a basis for sorting.
In this case, you can use lambda x
where x
are the elements in a
.
Subsequently, providing a tuple as a return result in the function allows the sort
to prioritize in sorting, thus what you need is this:
a.sort(key=lambda x: (len(str(x)), x))
In the above code, a
sorts first by len(str(x))
then by the value of x
Edit: Added explanation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.