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

如何排序AgeLabel数组同时让AgeCount数组保持对应关联

实现思路

  • 先将AgeLabel和AgeCount的对应位置元素绑定,避免排序过程中对应关系错乱
  • 提取AgeLabel每个元素中的年龄整数值作为排序依据
  • 排序完成后再将绑定的元素拆分回两个独立数组即可

Python 实现方案

# 原始输入数组
AgeLabel = ['43 yo', '12 yo', '33 yo', '25 yo']
AgeCount = [10, 20, 30, 40]

# 绑定→按年龄排序→拆分
AgeLabel, AgeCount = map(list, zip(*sorted(
    zip(AgeLabel, AgeCount),
    key=lambda item: int(item[0].split()[0])
)))

# 验证输出
print(AgeLabel)
print(AgeCount)

运行后输出结果和期望完全一致:

['12 yo', '25 yo', '33 yo', '43 yo']
[20, 40, 30, 10]

JavaScript 实现方案

// 原始输入数组
let AgeLabel = ['43 yo', '12 yo', '33 yo', '25 yo']
let AgeCount = [10, 20, 30, 40]

// 通过索引排序保证两个数组同步调整
const sortedIndices = AgeLabel
    .map((_, i) => i)
    .sort((a, b) => parseInt(AgeLabel[a]) - parseInt(AgeLabel[b]))

AgeLabel = sortedIndices.map(i => AgeLabel[i])
AgeCount = sortedIndices.map(i => AgeCount[i])

// 验证输出
console.log(AgeLabel)
console.log(AgeCount)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:09:01