按多个属性进行排序
创始人
2024-10-14 03:00:32
0

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

Python:

# 通过多个属性进行排序
def sort_by_multiple_attributes(items, attributes):
    return sorted(items, key=lambda x: [getattr(x, attr) for attr in attributes])

# 示例使用
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

people = [
    Person('Alice', 25),
    Person('Bob', 30),
    Person('Charlie', 20)
]

sorted_people = sort_by_multiple_attributes(people, ['age', 'name'])
for person in sorted_people:
    print(person.name, person.age)

Java:

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

// 示例类
class Person {
    String name;
    int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

// 自定义比较器
class PersonComparator implements Comparator {
    private List> comparators;

    public PersonComparator(List> comparators) {
        this.comparators = comparators;
    }

    @Override
    public int compare(Person p1, Person p2) {
        for (Comparator comparator : comparators) {
            int result = comparator.compare(p1, p2);
            if (result != 0) {
                return result;
            }
        }
        return 0;
    }
}

// 示例使用
public class Main {
    public static void main(String[] args) {
        List people = new ArrayList<>();
        people.add(new Person("Alice", 25));
        people.add(new Person("Bob", 30));
        people.add(new Person("Charlie", 20));

        List> comparators = new ArrayList<>();
        comparators.add(Comparator.comparing(Person::getAge));
        comparators.add(Comparator.comparing(Person::getName));

        Collections.sort(people, new PersonComparator(comparators));

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

以上示例演示了如何按照多个属性进行排序。在Python中,我们使用lambda表达式创建一个key函数,该函数返回一个包含多个属性的列表。在Java中,我们创建了一个自定义比较器,该比较器按顺序比较多个属性,并使用Collections.sort()方法进行排序。

相关内容

热门资讯

微信小程序黑科技免费!微乐家乡... 微信小程序黑科技免费!微乐家乡自建房辅助app(开挂)神器-真是教你存在有挂1、破解器简单,机器人操...
微乐小程序透视辅助!微信小程序... 微乐小程序透视辅助!微信小程序游戏充值破解(开挂)工具-原来必备有挂1、有没有辅助教程、有透视吗等服...
微乐小程序黑科技!微乐自建房脚... 微乐小程序黑科技!微乐自建房脚本免费下载入口(开挂)插件-果然有挂存在有挂1、有没有辅助教程、有透视...
微乐小程序透视挂!微乐河南家乡... 微乐小程序透视挂!微乐河南家乡麻将辅助脚本(开挂)app-其实教你是有挂1、不需要AI权限,帮助你快...
微乐小程序存在有挂!微信小程序... 微乐小程序存在有挂!微信小程序游戏充值破解(开挂)软件-本来推荐是真的挂1、下载好脚本下载之后点击打...
微乐小程序透视辅助!微乐小程序... 微乐小程序透视辅助!微乐小程序自建房插件免费(开挂)插件-切实解密是真的挂;能透视中分为三种模型:模...
微信小程序微乐破解器!微乐自建... 微信小程序微乐破解器!微乐自建房插件免费软件(开挂)方法-好像解迷存在有挂1、有没有辅助教程、有透视...
微信小程序黑科技免费!微乐自建... 微信小程序黑科技免费!微乐自建房脚本免费入口(开挂)app-一贯有挂是有挂1、辅助器安装包、辅助器2...
微信小程序黑科技免费!微信小程... 微信小程序黑科技免费!微信小程序微乐房间有技巧吗(开挂)教程-本来曝光存在有挂1、每一步都需要思考,...
微乐小程序存在有挂!微乐小程序... 微乐小程序存在有挂!微乐小程序辅助教程(开挂)方法-原来分享是有挂;1、每一步都需要思考,不同水平的...