HaR
HaR

Reputation: 1067

Append list based on another element in list and remove lists that contained the items

Let's say I have two lists like this:

list_all = [[['some_item'],'Robert'] ,[['another_item'],'Robert'],[['itemx'],'Adam'],[['item2','item3'],'Maurice]]

I want to combine the items together by their holder (i.e 'Robert') only when they are in separate lists. Ie in the end list_all should contain:

list_all = [[['some_name','something_else'],'Robert'],[['itemx'],'Adam'],[['item2','item3'],'Maurice]]

What is a fast and effective way of doing it? I've tried in different ways but I'm looking for something more elegant, more simplistic. Thank you

Upvotes: 0

Views: 57

Answers (3)

Veera Balla Deva
Veera Balla Deva

Reputation: 788

list_all = [[['some_item'],'Robert'] ,[['another_item'],'Robert'],[['itemx'],'Adam'],[['item2','item3'],'Maurice']]

dict_value = {}
for val in list_all:
    list_, name = val
    if name in dict_value:
        dict_value[name][0].extend(list_)
    else:      
        dict_value.setdefault(name,[list_, name])
print(list(dict_value.values()))
>>>[[['some_item', 'another_item'], 'Robert'],
 [['itemx'], 'Adam'],
 [['item2', 'item3'], 'Maurice']]

Upvotes: 0

Sam
Sam

Reputation: 845

You can try this, though it's quite similar to above answer but you can do this without importing anything.

list_all = [[['some_item'], 'Robert'], [['another_item'], 'Robert'], [['itemx'], 'Adam'], [['item2', 'item3'], 'Maurice']]

x = {}  # initializing a dictionary to store the data

for i in list_all:
    try:
        x[i[1]].extend(i[0])
    except KeyError:
        x[i[1]] = i[0]

list2 = [[j, i ] for i,j in x.items()]

Upvotes: 0

jpp
jpp

Reputation: 164693

Here is one solution. It is often better to store your data in a more structured form, e.g. a dictionary, rather than manipulate from one list format to another.

from collections import defaultdict

list_all = [[['some_item'],'Robert'],
            [['another_item'],'Robert'],
            [['itemx'],'Adam'],
            [['item2','item3'],'Maurice']]

d = defaultdict(list)

for i in list_all:
    d[i[1]].extend(i[0])

# defaultdict(list,
#             {'Adam': ['itemx'],
#              'Maurice': ['item2', 'item3'],
#              'Robert': ['some_item', 'another_item']})

d2 = [[v, k] for k, v in d.items()]

# [[['some_item', 'another_item'], 'Robert'],
#  [['itemx'], 'Adam'],
#  [['item2', 'item3'], 'Maurice']]

Upvotes: 4

Related Questions