Sort results non-lexicographically?

后端 未结 5 1703
轮回少年
轮回少年 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)
    
    0 讨论(0)
  • 2021-02-19 22:13

    I have found the code in the following link about natural sorting order very useful in the past:

    http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html

    0 讨论(0)
  • 2021-02-19 22:21

    You could split up the list, sort, then put it back together. Try something like this:

    numbers = sorted(int(i) for i in input_ if i.isdigit())
    nonnums = sorted(i for i in input_ if not i.isdigit())
    sorted_input = [str(i) for i in numbers] + nonnums
    

    You'll have to do something more complicated than isdigit if you can have non-integers.

    If this doesn't cover your "some are a combination of the two," please elaborate what that means and what output you expect from them.

    (Not tested, but should convey the idea.)

    0 讨论(0)
  • 2021-02-19 22:23

    For your specific case:

    def mySort(l):
        numbers = []
        words = []
        for e in l:
            try:
                numbers.append(int(e))
            except:
                words.append(e)
        return [str(i) for i in sorted(numbers)] + sorted(words)
    
    print mySort(input)
    
    0 讨论(0)
  • 2021-02-19 22:25

    1 - Install natsort module

    pip install natsort
    

    2 - Import natsorted

    >>> input = ['1', '10', '2', '0', '3', 'Hello', '100', 'Allowance']
    
    >>> from natsort import natsorted
    >>> natsorted(input)
    ['0', '1', '2', '3', '10', '100', 'Allowance', 'Hello']
    

    Source: https://pypi.python.org/pypi/natsort

    0 讨论(0)
提交回复
热议问题