字典是用python排序的,但不是用js排序的

2024-09-24 22:24:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个reactjs网站和一个用python编写的后端。现在,我有一张照片列表,我想按一个叫做“得分”的键来排序。你知道吗

在python中,我是这样做的(请告诉我这样做是否安全,我正在使用MySQLdb和Flask):

sql = "SELECT id, image_url, score, width, height FROM images ORDER BY score DESC LIMIT 10 OFFSET %s"
        conn.cursor.execute(sql, (offset,))
        images = conn.cursor.fetchall()
        dictImages = {}
        for image in images:
            dictImages[image[0]] = {"url": image[1], "score": image[2], "width": image[3], "height": image[4]}

我的字典是:

98: {'url': '62eb97f4496e9bd19755426bde78528f760f1e231545594871.jpg', 'score': 1459, 'width': 720, 'height': 1080}, 
100: {'url': '5a3a28f6f174d5995e6b6d6882e7c055c324f0081545595509.jpg', 'score': 1400, 'width': 1080, 'height': 1080}, 
97: {'url': '2516629bb990e9e8e6a4ccdaeae4048aa83119ee1545550157.JPG', 'score': 1390, 'width': 720, 'height': 899}, 
96: {'url': '6d3236ec3c88039ca534b81acad564e847ecb0621545549723.jpg', 'score': 1381, 'width': 640, 'height': 640}, 
99: {'url': '7a09101b84cd5618bfcdfa8423c16232788bf9691545595051.png', 'score': 1370, 'width': 1080, 'height': 940}

如您所见,它是按分数排序的,但js对象不是,它是:

  "96": {
    "height": 640, 
    "score": 1381, 
    "url": "6d3236ec3c88039ca534b81acad564e847ecb0621545549723.jpg", 
    "width": 640
  }, 
  "97": {
    "height": 899, 
    "score": 1390, 
    "url": "2516629bb990e9e8e6a4ccdaeae4048aa83119ee1545550157.JPG", 
    "width": 720
  }, 
  "98": {
    "height": 1080, 
    "score": 1459, 
    "url": "62eb97f4496e9bd19755426bde78528f760f1e231545594871.jpg", 
    "width": 720
  }, 
  "99": {
    "height": 940, 
    "score": 1370, 
    "url": "7a09101b84cd5618bfcdfa8423c16232788bf9691545595051.png", 
    "width": 1080
  }, 
  "100": {
    "height": 1080, 
    "score": 1400, 
    "url": "5a3a28f6f174d5995e6b6d6882e7c055c324f0081545595509.jpg", 
    "width": 1080
  }

这是按钥匙订购的。我怎样才能避免这个问题?我怎样才能有效地订购呢?(现在我只有几把钥匙,但应该还有更多……)

谢谢你的建议!你知道吗


Tags: imageurlsql排序pngconnwidthcursor
1条回答
网友
1楼 · 发布于 2024-09-24 22:24:49

创建arr时,使用的是常规对象({}),它不会按元素的插入顺序保留元素。相反,您可以使用^{}对象来执行以下操作:

var arr = new Map();

for(var i=0; ....)
    arr.set(i, VALUE);

相关问题 更多 >