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

如何按另一列表的词序对列表排序?支持不等长列表场景

按指定列表的顺序对另一个列表排序

可以通过构建目标顺序的索引映射来实现,这个方法同时支持两个列表长度一致或不一致的场景。

核心思路

  1. 先把参考列表x中的每个元素映射到它的索引位置,形成一个字典,这样能快速获取每个元素的排序优先级。
  2. 使用这个字典作为排序键,对列表y进行排序。

代码示例

场景1:两个列表长度一致

x = ['Apple', 'Banana', 'Coconut']
y = ['Banana', 'Coconut', 'Apple']

# 构建元素到索引的映射
order_map = {item: idx for idx, item in enumerate(x)}
# 按x的顺序排序y
y_sorted = sorted(y, key=lambda item: order_map[item])

print(y_sorted)  # 输出: ['Apple', 'Banana', 'Coconut']

场景2:两个列表长度不一致

x = ['Apple', 'Banana', 'Coconut']
y = ['Coconut', 'Apple']

order_map = {item: idx for idx, item in enumerate(x)}
y_sorted = sorted(y, key=lambda item: order_map[item])

print(y_sorted)  # 输出: ['Apple', 'Coconut']

扩展处理:y包含x中没有的元素

如果y里存在x没有的元素,直接用上面的代码会抛出KeyError。可以给映射添加默认值,把这类元素放到排序结果的末尾:

x = ['Apple', 'Banana', 'Coconut']
y = ['Coconut', 'Durian', 'Apple']

order_map = {item: idx for idx, item in enumerate(x)}
# 用len(x)作为默认索引,让不在x里的元素排最后
y_sorted = sorted(y, key=lambda item: order_map.get(item, len(x)))

print(y_sorted)  # 输出: ['Apple', 'Coconut', 'Durian']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:25:22