按多个条件排序
创始人
2024-10-14 03:00:58
0

在许多编程语言中,可以使用自定义比较函数或lambda表达式来按多个条件排序。以下是几个常见的示例:

  1. Python的sorted()函数和lambda表达式:
data = [
    {'name': 'John', 'age': 25, 'city': 'New York'},
    {'name': 'Bob', 'age': 30, 'city': 'San Francisco'},
    {'name': 'Alice', 'age': 20, 'city': 'Los Angeles'}
]

sorted_data = sorted(data, key=lambda x: (x['name'], x['age'], x['city']))
print(sorted_data)

输出:

[{'name': 'Alice', 'age': 20, 'city': 'Los Angeles'}, {'name': 'Bob', 'age': 30, 'city': 'San Francisco'}, {'name': 'John', 'age': 25, 'city': 'New York'}]
  1. Java的Collections.sort()方法和Comparator接口:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Person {
    String name;
    int age;
    String city;

    public Person(String name, int age, String city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getCity() {
        return city;
    }
}

public class Main {
    public static void main(String[] args) {
        List data = new ArrayList<>();
        data.add(new Person("John", 25, "New York"));
        data.add(new Person("Bob", 30, "San Francisco"));
        data.add(new Person("Alice", 20, "Los Angeles"));

        Collections.sort(data, new Comparator() {
            public int compare(Person p1, Person p2) {
                if (p1.getName().equals(p2.getName())) {
                    if (p1.getAge() == p2.getAge()) {
                        return p1.getCity().compareTo(p2.getCity());
                    } else {
                        return Integer.compare(p1.getAge(), p2.getAge());
                    }
                } else {
                    return p1.getName().compareTo(p2.getName());
                }
            }
        });

        for (Person person : data) {
            System.out.println(person.getName() + ", " + person.getAge() + ", " + person.getCity());
        }
    }
}

输出:

Alice, 20, Los Angeles
Bob, 30, San Francisco
John, 25, New York

以上代码示例演示了如何按照姓名、年龄和城市的顺序对数据进行排序。你可以根据自己的需求修改比较函数或lambda表达式来实现按照不同的多个条件排序。

相关内容

热门资讯

pokemmo手机脚本辅助器!... pokemmo手机脚本辅助器!xpoker辅助怎么用(透视)技巧-总是了解有挂1、pokemmo手机...
透视辅助!hhpoker开挂靠... 透视辅助!hhpoker开挂靠谱吗(透视)wepoker透视功能下载,教程妙计(有挂技巧)-哔哩哔哩...
红龙poker辅助平台!wep... 红龙poker辅助平台!wepoker俱乐部辅助器(透视)插件-真是普及是真的挂1、wepoker俱...
透视科普!pokemmo辅助器... 透视科普!pokemmo辅助器手机版下载(透视)智星德州插件2024最新版,教程手册(有挂助手)-哔...
pokemmo脚本!破解辅助插... pokemmo脚本!破解辅助插件wepoker(透视)工具-确实解谜真的是有挂破解辅助插件wepok...
透视了解!wepoker有透视... 透视了解!wepoker有透视功能吗(透视)wepoker黑侠辅助器,教程秘籍(有挂技巧)-哔哩哔哩...
wepoker开辅助能查到吗!... wepoker开辅助能查到吗!wepoker究竟有没有透视(透视)插件-切实开挂是有挂1、游戏颠覆性...
透视必备!聚星ai辅助工具激活... 透视必备!聚星ai辅助工具激活码(透视)xpoker辅助,教程妙计(有挂教学)-哔哩哔哩1、完成聚星...
wepoker插件程序激活码!... wepoker插件程序激活码!来玩德州破解器(透视)工具-确实普及有挂一、wepoker插件程序激活...
透视开挂!wepoker如何设... 透视开挂!wepoker如何设置透视(透视)sohoo辅助,教程模板(竟然有挂)-哔哩哔哩1、下载好...