0

Say I have a list of list like this: (suppose you have no idea how many lists in this list)

list=[['food','fish'],['food','meat'],['food','veg'],['sports','football']..]

how can I merge the items in the list like the following:

list=[['food','fish','meat','veg'],['sports','football','basketball']....]

i.e, merge all the nested lists into the same list if they contain one of the same items.

0

2 Answers 2

4

Use defaultdict to make a dictionary that maps a type to values and then get the items:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> items = [['food','fish'],['food','meat'],['food','veg'],['sports','football']]
>>> for key, value in items:
...     d[key].append(value)
...     
>>> [[key] + values for key, values in d.items()]
    [['food', 'fish', 'meat', 'veg'], ['sports', 'football']]
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh +1 - the relationship seems obvious now you've posted this answer - thanks :) (must need more coffee)
2

The "compulsory" alternative to defaultdict which can work better for data that's already in order of the key and if you don't want to build data structures on it (ie, just work on groups)...

data = [['food','fish'],['food','meat'],['food','veg'],['sports','football']]

from itertools import groupby
print [[k] + [i[1] for i in v] for k, v in groupby(data, lambda L: L[0])]

But defaultdict is more flexible and easier to understand - so go with @Blender's answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.