以下是一个示例代码,演示如何按多个属性和条件对对象列表进行排序和分组。
首先,我们定义一个名为Person的类,它具有name,age和country属性。
class Person:
def __init__(self, name, age, country):
self.name = name
self.age = age
self.country = country
然后,我们创建一个对象列表,其中包含一些Person对象。
people = [
Person("Alice", 25, "USA"),
Person("Bob", 30, "Canada"),
Person("Charlie", 20, "USA"),
Person("David", 35, "Canada"),
Person("Eve", 25, "USA")
]
现在,假设我们要首先按国家进行分组,然后按年龄进行排序。我们可以使用Python的itertools.groupby
函数来实现分组。
import itertools
# 先按国家分组
people.sort(key=lambda x: x.country)
groups = []
for key, group in itertools.groupby(people, key=lambda x: x.country):
groups.append(list(group))
现在,我们已经将人员列表按国家分组,并将每个组存储在groups
列表中。
接下来,我们可以在每个组中按年龄进行排序。
for group in groups:
group.sort(key=lambda x: x.age)
现在,每个组都按照国家和年龄排序。
最后,我们可以打印排序后的结果。
for group in groups:
print(f"Group: {group[0].country}")
for person in group:
print(f" {person.name}, {person.age}")
完整的示例代码如下:
import itertools
class Person:
def __init__(self, name, age, country):
self.name = name
self.age = age
self.country = country
people = [
Person("Alice", 25, "USA"),
Person("Bob", 30, "Canada"),
Person("Charlie", 20, "USA"),
Person("David", 35, "Canada"),
Person("Eve", 25, "USA")
]
people.sort(key=lambda x: x.country)
groups = []
for key, group in itertools.groupby(people, key=lambda x: x.country):
groups.append(list(group))
for group in groups:
group.sort(key=lambda x: x.age)
for group in groups:
print(f"Group: {group[0].country}")
for person in group:
print(f" {person.name}, {person.age}")
输出结果如下:
Group: Canada
Bob, 30
David, 35
Group: USA
Charlie, 20
Alice, 25
Eve, 25
上一篇:按多个属性过滤JSON数据
下一篇:按多个属性进行排序