在许多编程语言中,可以使用自定义比较函数或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'}]
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表达式来实现按照不同的多个条件排序。