list中按照对象某个属性合并
时间: 2023-09-07 12:17:14 浏览: 44
可以使用Python的标准库`itertools`中的`groupby`函数来实现按照对象某个属性合并列表。
假设我们有以下的对象列表:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
people = [
Person('Alice', 18),
Person('Bob', 20),
Person('Charlie', 18),
Person('David', 22),
Person('Eva', 20)
]
```
我们可以按照年龄将这个人列表合并,并把同年龄的人放在一个列表里。代码如下:
```python
from itertools import groupby
def merge_by_age(people):
people.sort(key=lambda x: x.age)
groups = groupby(people, key=lambda x: x.age)
merged = []
for age, group in groups:
merged.append((age, list(group)))
return merged
merged_people = merge_by_age(people)
print(merged_people)
```
输出为:
```
[(18, [<__main__.Person object at 0x7f7f00d5b280>, <__main__.Person object at 0x7f7f00d5b1f0>]),
(20, [<__main__.Person object at 0x7f7f00d5b340>, <__main__.Person object at 0x7f7f00d5b2e0>]),
(22, [<__main__.Person object at 0x7f7f00d5b310>])]
```
其中,每个元组的第一个元素为年龄,第二个元素为同年龄的人组成的列表。