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

如何在Haskell中先按第二个元素再按第一个元素排序元组数组

元组数组多条件排序实现方案

多条件排序的核心逻辑是:优先按高优先级字段排序,当该字段值相等时,再按次优先级字段排序。以下是主流编程语言的实现示例:

Python 实现

利用sorted()函数的key参数,返回一个包含排序优先级的元组(先写高优先级字段,再写次优先级字段),Python会自动按元组内元素的顺序依次比较:

# 示例元组数组
tuple_list = [(3, 2), (1, 2), (2, 1)]

# 升序排序:先按第二个元素,再按第一个元素
sorted_asc = sorted(tuple_list, key=lambda x: (x[1], x[0]))
print(sorted_asc)  # 输出: [(2, 1), (1, 2), (3, 2)]

# 降序排序:第二个元素降序,第一个元素升序
sorted_desc = sorted(tuple_list, key=lambda x: (-x[1], x[0]))
print(sorted_desc)  # 输出: [(1, 2), (3, 2), (2, 1)]

JavaScript 实现

通过Array.sort()自定义比较函数,先判断第二个元素是否相等,不等则直接返回差值;相等时再比较第一个元素的差值:

// 示例元组数组
const tupleArray = [[3, 2], [1, 2], [2, 1]];

// 升序排序
tupleArray.sort((a, b) => {
  if (a[1] !== b[1]) {
    return a[1] - b[1];
  }
  return a[0] - b[0];
});
console.log(tupleArray); // 输出: [[2, 1], [1, 2], [3, 2]]

// 降序排序
tupleArray.sort((a, b) => {
  if (a[1] !== b[1]) {
    return b[1] - a[1];
  }
  return b[0] - a[0];
});
console.log(tupleArray); // 输出: [[3, 2], [1, 2], [2, 1]]

Java 实现

使用Comparator接口自定义比较规则,先对比第二个元素,相等时再对比第一个元素:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class TupleSortDemo {
    public static void main(String[] args) {
        List<int[]> tupleList = new ArrayList<>();
        tupleList.add(new int[]{3, 2});
        tupleList.add(new int[]{1, 2});
        tupleList.add(new int[]{2, 1});

        // 升序排序
        Collections.sort(tupleList, (a, b) -> {
            if (a[1] != b[1]) {
                return Integer.compare(a[1], b[1]);
            }
            return Integer.compare(a[0], b[0]);
        });

        // 打印结果
        for (int[] tuple : tupleList) {
            System.out.printf("(%d, %d) ", tuple[0], tuple[1]);
        }
        // 输出: (2, 1) (1, 2) (3, 2)
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:35:34