在属性等于的数组中对对象的子数组进行分组-Python

鲍登

我有一个数组,subarray如果键值对等于,则试图将对象s组合在一起userID

给我一个对象,每个对象带有该对象的userID所有子数组userID

即使在通过SO拖网之后,我似乎也无法弄清楚该如何做。

如何userID将的相同子数组分组(数据更改,因此我需要使用for循环)

谢谢您的帮助。

该数组如下所示:

      [  
       {  
          'name':'James',
          'lastname':'Bond',
          'userID': 1001,
          'subarray':[  
             {  
                'color':'blue',
                'animal':'dog'
             }
          ]
       },
       {  
          'name':'James',
          'lastname':'Bond',
          'userID': 1001,
          'subarray':[  
             {  
                'color':'red',
                'animal':'cat'
             }
          ]
       },
       {  
          'name':'Billy',
          'lastname':'King',
          'userID': 1004,
          'subarray':[  
             {  
                'color':'green',
                'animal':'fish'
             }
          ]
       }
    ]

我想要这样的数组:

      [  
       {  
          'name':'James',
          'lastname':'Bond',
          'userID': 1001,
          'subarray':[  
             {  
                'color':'blue',
                'animal':'dog'
             },
             {  
                'color':'red',
                'animal':'cat'
             }
          ]
       },
       {  
          'name':'Billy',
          'lastname':'King',
          'userID': 1004,
          'subarray':[  
             {  
                'color':'green',
                'animal':'fish'
             }
          ]
       }
    ]
拉克什

使用简单的迭代。

例如:

result = {}
for item in data:
    if item["userID"] not in result:
        result[item["userID"]] = {'name':item["name"], 'lastname':item["lastname"],'userID': item["userID"],'subarray':[]}
    result[item["userID"]]['subarray'].append(item["subarray"])

print(list(result.values()))

输出:

[{'lastname': 'Bond',
  'name': 'James',
  'subarray': [[{'animal': 'dog', 'color': 'blue'}],
               [{'animal': 'cat', 'color': 'red'}]],
  'userID': 1001},
 {'lastname': 'King',
  'name': 'Billy',
  'subarray': [[{'animal': 'fish', 'color': 'green'}]],
  'userID': 1004}]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在python中按键对对象数组进行分组

通过子属性对对象数组进行分组

如何根据对象中的属性对对象数组进行分组

Python-如何按照指定的属性顺序对对象数组进行双重排序?

如何使用lodash对对象数组中的属性进行分组?

如何在Python中按日期时间对对象数组进行排序?

在javascript中对对象数组进行分组

在AngularJS中对对象数组进行分组

如何通过作为数组的子属性有效地对对象数组进行分组?

Python:如何根据对象的特征或属性对对象列表进行分组?

在 python 2.7 中对字典数组进行分组

通过通用属性对对象进行分组,将其余属性合并为数组中的单独对象

如何通过数组中嵌套的子对象对象对对象进行分组

通过通用键对对象数组进行分组,将嵌套属性合并到数组中

如何基于Javascript中的多个数组属性对对象数组进行分组

Python,按最低子对象属性对对象列表进行排序

按属性 javascript 对对象数组进行分组

按属性对对象数组进行分组并对值求和

如何按对象的值对对象数组进行分组并在新属性中求和

根据对象数组中的相似值对对象进行分组

在javascript中按子数组属性值对对象数组进行排序

如何基于香草javascript中的属性对对象数组进行分组

如何对对象数组中的多个属性值进行计数和分组?

如何对对象数组中的值进行分组和求和?

在javascript中按id对对象数组进行分组

按键对对象数组进行分组

如何对对象数组进行分组?

如何根据ng2-order-pipe中的子属性对对象数组进行排序

Python:根据对象的属性对对象列表进行排序