Group 2d array by name

user2286089 :

how to separate the data below into 3d array by the different English names.

The actual data

[['سمو', 'name']
 ['أله', 'name']
 ['حسن', 'name']
 ['قبس', 'brand']
 ['وسم', 'brand']]

The Expectation data

[[['سمو', 'name']
 ['أله', 'name']
 ['حسن', 'name']],
 [['قبس', 'brand']
 ['وسم', 'brand']]]

The code I have

old_data = [['سمو', 'name'],
            ['أله', 'name'],
            ['حسن', 'name'],
            ['قبس', 'brand'],
            ['وسم', 'brand']]

Simon Brahan :

itertools can do this for you.

import itertools

grouped_data = itertools.groupby(old_data, lambda item: item[1])

groupby returns an iterator rather than a list; you can either loop through it, or flatten it like so:

flattened_groups = [list(group) for label, group in grouped_data]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12645&siteId=1