Sort a list of numerical strings in ascending order

前端 未结 2 2049
忘了有多久
忘了有多久 2020-12-07 22:25

I have created a sqlite database which has a table which stores temperature values. The temperature values are written to the database in ascending order for the first time.

2条回答
  •  失恋的感觉
    2020-12-07 23:00

    The recommended approach in this case is to sort the data in the database, adding an ORDER BY at the end of the query that fetches the results, something like this:

    SELECT temperature FROM temperatures ORDER BY temperature ASC;  -- ascending order
    SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order
    

    If for some reason that is not an option, you can change the sorting order like this in Python:

    templist = [25, 50, 100, 150, 200, 250, 300, 33]
    sorted(templist, key=int)               # ascending order
    > [25, 33, 50, 100, 150, 200, 250, 300]
    sorted(templist, key=int, reverse=True) # descending order
    > [300, 250, 200, 150, 100, 50, 33, 25]
    

    As has been pointed in the comments, the int key (or float if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.

提交回复
热议问题