How order data by column?

198
1
Jump to solution
04-20-2021 02:50 PM
Labels (3)
Radzhabad
New Contributor II

There is a table with two columns. I want to sort it by 1st column, but there is a problem with the data type. Sort Ascending. If we make a column of type INT, then my slash will be lost. And if you leave it as STRING, the sorting is wrong.

INDEX;TEXT
2;ТП 12-4/2502-2-ЖБ
20;ТП 12-4/2502-20-ЖБ
2/1;ТП 12-4/2502-2/1-ЖБ
21;ТП 12-4/2502-21-ЖБ
3;ТП 12-4/2502-3-ЖБ

This is what you should get at the output.

INDEX;TEXT
2;ТП 12-4/2502-2-ЖБ
2/1;ТП 12-4/2502-2/1-ЖБ
3;ТП 12-4/2502-3-ЖБ
20;ТП 12-4/2502-20-ЖБ
21;ТП 12-4/2502-21-ЖБ

How make it with SearchCursor

Tags (1)
0 Kudos
1 Solution

Accepted Solutions
DanPatterson
MVP Esteemed Contributor

It is called a "natural sort"

def natsort(text_lst):
    """natural sort returns text containing numbers sorted considering the
    :  number in the sequence.
    :originals used lambda expressions
    :  convert = lambda text: int(text) if text.isdigit() else text
    :  a_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
    """
    import re
    def convert(text):
        return int(text) if text.isdigit() else text

    def a_key(key):
        return [convert(c) for c in re.split('([0-9]+)', key)]

    return sorted(text_lst, key=a_key)


a = ['a1', 'a20', 'a2', 'a10']
vals = natsort(a)
print("natural sort - \n{}".format(vals))

natural sort - 
['a1', 'a2', 'a10', 'a20']

... sort of retired...

View solution in original post

0 Kudos
1 Reply
DanPatterson
MVP Esteemed Contributor

It is called a "natural sort"

def natsort(text_lst):
    """natural sort returns text containing numbers sorted considering the
    :  number in the sequence.
    :originals used lambda expressions
    :  convert = lambda text: int(text) if text.isdigit() else text
    :  a_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
    """
    import re
    def convert(text):
        return int(text) if text.isdigit() else text

    def a_key(key):
        return [convert(c) for c in re.split('([0-9]+)', key)]

    return sorted(text_lst, key=a_key)


a = ['a1', 'a20', 'a2', 'a10']
vals = natsort(a)
print("natural sort - \n{}".format(vals))

natural sort - 
['a1', 'a2', 'a10', 'a20']

... sort of retired...
0 Kudos