tksheet icon indicating copy to clipboard operation
tksheet copied to clipboard

Rows sorting?

Open majki09 opened this issue 2 years ago • 3 comments

How do I sort rows with some column?

majki09 avatar Mar 27 '24 19:03 majki09

Hello,

There is currently no in-built way to do this, it would require getting the table and index data which is a list of lists, the sublists are rows, sorting this and then setting the table and index data to the newly sorted data

Once you have the data from the table a basic way of sorting the list of lists by a column would be something like this: https://stackoverflow.com/a/4174955/7655687

There are more advanced methods which take into account digits utilising the sort() methods key= parameter

For example:

def sort():
    col = 1
    sort_key = lambda row: [
            int(c) if c.isdigit() else c.lower() for c in re.split("([0-9]+)", f"{row[col]}")
        ]
    span = sheet[:].options(index=True)
    sheet.set_data(span, data=sorted(span.data, key=sort_key))

You will have to research what key you want to use as I am not experienced with sorting, natural sorting etc.

There are some libraries which handle it pretty well, for example: https://github.com/SethMMorton/natsort

I hope this helps!

ragardner avatar Mar 28 '24 09:03 ragardner

Is it that simple? Thank you so much for the answer and all your effort for tksheet 😀

majki09 avatar Apr 10 '24 04:04 majki09

Would love to have this as a function available to the sheet itself. at least a simple lexicographic sort on one column for example would be easy to implement. #238

TweetleDee916 avatar Feb 06 '25 15:02 TweetleDee916