-3

I have this:

 a = [['huhu', 'dow'], ['haha', 'dow'], ['haha', 'pow'], ['haha', 'dow'],  ['haha', 'mat'], ['hihi', 'dow'], ['hihi', 'pow']]

and I want

[['huhu', 'dow'], ['haha', 'dow', 'pow', 'dow', 'mat'], ['hihi', 'dow'], ['hihi', 'pow']]

AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
Jeanmulin
  • 17
  • 1
  • 3
    why `['hihi', 'dow'], ['hihi', 'pow']` and not `['hihi', 'dow', 'pow']`? + Why not use a dictionary? Looks like you are dealing with *keys*.. – Ma0 Jun 12 '18 at 07:03
  • 2
    What's the logic behind your expected output? Also, please add your code that you've tried so far. SO is not a homework solving service. People here can help you when they know that you've already tried to solve your problem by yourself and for any reason you couldn't. – Mazdak Jun 12 '18 at 07:04
  • Can you explain why the last two entries of your dictionary aren't combined? Seems to break your pattern – user3483203 Jun 12 '18 at 07:07
  • Possible duplicate of [Merge lists that share common elements](https://stackoverflow.com/questions/4842613/merge-lists-that-share-common-elements) – AGN Gazer Jun 12 '18 at 07:08

1 Answers1

2

I would recommend using a dictionary here, it is much cleaner. In particular I would recommend a collections.defaultdict:

from collections import defaultdict
dct = defaultdict(list)

for key, *values in a:
    dct[key].extend(values)

Output:

defaultdict(list,
            {'huhu': ['dow'],
             'haha': ['dow', 'pow', 'dow', 'mat'],
             'hihi': ['dow', 'pow']})

If you want this as a list, it is a fairly simple comprehension:

[[k, *v] for k, v in dct.items()]

# [['huhu', 'dow'], ['haha', 'dow', 'pow', 'dow', 'mat'], ['hihi', 'dow', 'pow']]
user3483203
  • 50,081
  • 9
  • 65
  • 94
  • and if OP for some reason insists on the output, he can use `res = [[k] + v for k, v in dct.items()]`. – Ma0 Jun 12 '18 at 07:14