Created
February 27, 2020 16:19
-
-
Save AntiKnot/bfc9bc8a9331ea0b7dc470df86c35c68 to your computer and use it in GitHub Desktop.
Python sort list by function with two arguments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import functools | |
| from typing import List | |
| class Solution(object): | |
| def largest_nums(self, nums: List[int]) -> str: | |
| snums = [str(item) for item in nums] | |
| snums.sort(key=functools.cmp_to_key(self.cmp), reverse=True) | |
| _res = "" | |
| for i in snums: | |
| _res += i | |
| return _res | |
| @staticmethod | |
| def cmp(s1, s2): | |
| s12 = s1 + s2 | |
| s21 = s2 + s1 | |
| if s12 < s21: | |
| return -1 | |
| elif s12 > s21: | |
| return 1 | |
| return 0 | |
| """ | |
| # if you dont want use functools | |
| # https://stackoverflow.com/a/12749495 | |
| def make_comparator(less_than): | |
| def compare(x, y): | |
| if less_than(x, y): | |
| return -1 | |
| elif less_than(y, x): | |
| return 1 | |
| else: | |
| return 0 | |
| return compare | |
| """ | |
| if __name__ == '__main__': | |
| solution = Solution() | |
| nums = [3, 30, 34, 5, 9] | |
| res = solution.largest_nums(nums) | |
| print(res) | |
| """ | |
| reference | |
| https://stackoverflow.com/questions/49950997/python-sort-list-by-function-with-multiple-arguments | |
| https://stackoverflow.com/questions/12749398/using-a-comparator-function-to-sort | |
| """ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment