You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DolphinDB是否有Python argsort等效函数?如何实现字典排序?

在DolphinDB中实现城市人口字典的创建、筛选与排序

完整实现代码

// 1. 创建城市-人口字典(人口单位:万)
cityPopulation = dict(
    ["北京", "上海", "广州", "深圳", "成都", "杭州"],
    [2154, 2428, 1530, 1344, 1658, 1193]
)

// 2. 筛选人口超过1000万的城市
filteredCities = dict(
    keys(cityPopulation)[values(cityPopulation) > 1000],
    values(cityPopulation)[values(cityPopulation) > 1000]
)

// 3. 按人口降序排序:替代argsort的实现
sortedIndices = xdesc(values(filteredCities))
sortedCities = dict(
    keys(filteredCities)[sortedIndices],
    values(filteredCities)[sortedIndices]
)

// 输出结果
print(sortedCities)

核心问题解决:替代argsort的方案

DolphinDB中没有argsort函数,你可以用以下两种方式实现排序:

  1. 使用xdesc/xasc获取排序索引

    • xdesc(values(字典)):返回字典值按降序排列对应的原索引位置
    • xasc(values(字典)):返回字典值按升序排列对应的原索引位置
    • 通过这些索引重新提取键和值,即可得到排序后的字典
  2. 转成表处理(可读性更强)
    如果觉得字典操作繁琐,可以先将字典转换为表,用SQL语法完成筛选和排序,再转回字典:

// 转表处理流程
cityTable = table(keys(cityPopulation) as city, values(cityPopulation) as population)
filteredTable = select * from cityTable where population > 1000
sortedTable = select * from filteredTable order by population desc
sortedCities = dict(sortedTable.city, sortedTable.population)

内容的提问来源于stack exchange,提问作者Elsa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 23:16:00