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

如何对一个列表排序并让另一个列表同步发生相同排序变化?

解决方法

你需要保持两个列表的元素对应关系,不能单独对水果列表排序,否则会打乱颜色的匹配。这里有两种简单的实现方式:

方法1:打包配对后排序再拆分

先把水果和对应的颜色打包成元组,按水果名称排序后,再拆分成两个独立列表:

# 原始列表
fruits = ["Banana", "Apple", "Orange"]
colors = ["Yellow", "Red", "Orange"]

# 打包并按水果排序
sorted_pairs = sorted(zip(fruits, colors), key=lambda item: item[0])

# 拆分回排序后的列表(如果需要列表类型,转成list即可)
sorted_fruits, sorted_colors = zip(*sorted_pairs)
sorted_fruits = list(sorted_fruits)
sorted_colors = list(sorted_colors)

# 输出结果
print(sorted_fruits)  # ['Apple', 'Banana', 'Orange']
print(sorted_colors)  # ['Red', 'Yellow', 'Orange']

方法2:通过排序索引同步

先获取水果列表排序后的索引顺序,再用这个索引重新排列两个列表:

# 原始列表
fruits = ["Banana", "Apple", "Orange"]
colors = ["Yellow", "Red", "Orange"]

# 获取按水果排序后的索引位置
sorted_indices = sorted(range(len(fruits)), key=lambda i: fruits[i])

# 根据索引重新生成排序后的列表
sorted_fruits = [fruits[i] for i in sorted_indices]
sorted_colors = [colors[i] for i in sorted_indices]

# 输出结果
print(sorted_fruits)  # ['Apple', 'Banana', 'Orange']
print(sorted_colors)  # ['Red', 'Yellow', 'Orange']

两种方法的核心思路都是基于第一个列表的排序规则,同步调整第二个列表的元素顺序,确保对应关系不丢失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:35:17