按属性将列表项分组在一个对象中
创始人
2024-11-05 18:01:39
0

以下是一个示例代码,将列表项按属性分组在一个对象中:

def group_items_by_attribute(items, attribute):
    grouped_items = {}
    for item in items:
        item_attribute = getattr(item, attribute)
        if item_attribute in grouped_items:
            grouped_items[item_attribute].append(item)
        else:
            grouped_items[item_attribute] = [item]
    return grouped_items

# 示例使用
class Item:
    def __init__(self, name, category):
        self.name = name
        self.category = category
    
    def __repr__(self):
        return f"Item(name='{self.name}', category='{self.category}')"

items = [
    Item('Item 1', 'Category A'),
    Item('Item 2', 'Category B'),
    Item('Item 3', 'Category A'),
    Item('Item 4', 'Category B'),
    Item('Item 5', 'Category C'),
]

grouped_items = group_items_by_attribute(items, 'category')
print(grouped_items)

输出结果:

{
    'Category A': [
        Item(name='Item 1', category='Category A'),
        Item(name='Item 3', category='Category A')
    ],
    'Category B': [
        Item(name='Item 2', category='Category B'),
        Item(name='Item 4', category='Category B')
    ],
    'Category C': [
        Item(name='Item 5', category='Category C')
    ]
}

以上代码中,我们定义了一个 group_items_by_attribute 函数,该函数接受一个列表 items 和一个属性名 attribute。函数通过循环遍历列表中的每个项,并使用 getattr 函数获取该项的指定属性值。然后,我们检查该属性值是否已经存在于 grouped_items 字典中,如果存在,则将该项添加到对应的列表中,否则创建一个新的列表,并将该项添加到其中。最终,函数返回一个包含分组项的字典。

相关内容

热门资讯

避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
安装了Anaconda之后找不... 在安装Anaconda后,如果找不到Jupyter Notebook,可以尝试以下解决方法:检查环境...
omi系统和安卓系统哪个好,揭... OMI系统和安卓系统哪个好?这个问题就像是在问“苹果和橘子哪个更甜”,每个人都有自己的答案。今天,我...
原生ios和安卓系统,原生对比... 亲爱的读者们,你是否曾好奇过,为什么你的iPhone和安卓手机在操作体验上有着天壤之别?今天,就让我...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...