Sort results non-lexicographically?

后端 未结 5 1633
轮回少年
轮回少年 2021-02-19 21:29

I\'m trying to display some results in a human-readable way. For the purposes of this question, some of them are numbers, some are letters, some are a combination of the two.

5条回答
  •  我寻月下人不归
    2021-02-19 22:05

    This will do it. For purposes of comparison, it converts strings that can be converted to an integer to that integer, and leaves other strings alone:

    def key(s):
        try:
            return int(s)
        except ValueError:
            return s
    
    sorted_input = sorted(input, key=key)
    

提交回复
热议问题