按升序对数字字符串列表进行排序

编程入门 行业动态 更新时间:2024-10-26 16:32:33
本文介绍了按升序对数字字符串列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我创建了一个sqlite数据库,该数据库具有一个存储温度值的表.第一次将温度值以升序写入数据库.然后,我从数据库中将温度值读取到一个列表中,然后将该列表添加到组合框中以选择温度-可以正常工作.

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. Then I read the temperature values from the database into a list and then add that list to a combo box to select temperatures - works fine.

结果列表为:

templist = ['25', '50', '100', '150', '200', '250', '300'].

然后,我向数据库添加一个新的温度值,例如"33".

Then I add a new temperature value, say, '33' to the database.

它被附加到表的末尾.如果我现在阅读温度,列表将变为:

It gets appended to the end of the table. If I read the temperatures now, the list will become:

['25', '50', '100', '150', '200', '250', '300', '33'].

如果我执行templist.sort()或sorted(templist),则最终结果为

If I do templist.sort() or sorted(templist), the end result is

['150', '200', '25', '250', '300', '33', '50']

有没有简单的方法可以按升序对列表进行排序,以便得到:

Is there any simple way to sort the list in ascending order so that I get:

['25', '33', '50', '100', '150', '200', '250', '300']

推荐答案

在这种情况下,推荐的方法是对数据库中的数据进行排序,在获取结果的查询末尾添加ORDER BY,例如这个:

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

如果由于某种原因不是一种选择,则可以在Python中像这样更改排序顺序:

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]

正如注释中指出的那样,如果接收到的数据为string类型,则需要int键(如果存储的是带有小数的值,则为float),以便正确地对数据进行排序. d将温度值存储为字符串非常奇怪,如果是这种情况,请返回并从根本上解决问题,并确保要存储的温度是数字.

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.

更多推荐

按升序对数字字符串列表进行排序

本文发布于:2023-10-18 03:24:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502935.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:升序   字符串   数字   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!