我想将集合中某个属性相同的对象形成一个新的集合,请给我实例代码
时间: 2023-06-03 19:05:46 浏览: 50
Sure, here's an example code in Python:
```
# List of objects
list_of_objects = [
{'name': 'John', 'age': 25},
{'name': 'Jane', 'age': 25},
{'name': 'Bob', 'age': 30},
{'name': 'Alice', 'age': 30}
]
# Group objects by age
groups = {}
for obj in list_of_objects:
age = obj['age']
if age not in groups:
groups[age] = []
groups[age].append(obj)
# Print groups
for age, group in groups.items():
print(f'Age {age}:')
for obj in group:
print(f'- {obj["name"]}')
```
This code will group the objects in the `list_of_objects` list by age, and create a dictionary called `groups` where each key represents an age and the corresponding value is a list of objects with that age. Finally, it prints the groups in the console.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)