3

For example I have a list which looks like this one

# [
# [elem1, ... comment11]
# [elem1, ... comment12]
# ...
# [elem2, ... comment21]
# ...
# ]

And I should make from this something similar that:

# [
# [elem1, ... [comment11, comment12]]
# [elem2, ... [comment21, ...]]
# ...
# ]

Where just unlike list's elements (only last elements of each list) will be concatenated to one new list.

2 Answers2

4

Using itertools.groupby:

>>> import itertools
>>> import operator
>>> a_list = [
...     ['elem1', 'other_item1', 'other_item1', 'comment11'],
...     ['elem1', 'other_item2', 'other_item2', 'comment12'],
...     ['elem2', 'other_item3', 'other_item3', 'comment21'],
... ]
>>> new_list = []
>>> for _, grp in itertools.groupby(a_list, key=operator.itemgetter(0)):
...     grp = list(grp)
...     new_list.append(grp[0][:-1] + [[item[-1] for item in grp]])
... 
>>> new_list
[['elem1', 'other_item1', 'other_item1', ['comment11', 'comment12']],
 ['elem2', 'other_item3', 'other_item3', ['comment21']]]
falsetru
  • 357,413
  • 63
  • 732
  • 636
3

You are looking for defaultdict. From the documentation:

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
        d[k].append(v)

>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

To adapt this to your question the code might look like this:

>>> s = [['elem1', 'comment11'],['elem1', 'comment12'],['elem2', 'comment21']]
>>> d = defaultdict(list)
>>> for l in s:
        d[l[0]].append(*l[1:])
>>> d.items()
[('elem2', ['comment21']), ('elem1', ['comment11', 'comment12'])]
Jason Sperske
  • 29,816
  • 8
  • 73
  • 124
  • The OP has a list of lists, not a list of tuples, so you'd want something like `((x[0], x[-1]) for x in inputList)` to generate the tuples. – Frerich Raabe Dec 02 '13 at 08:14
  • @FrerichRaabe did I address your comment? (Still learning Python) – Jason Sperske Dec 02 '13 at 08:23
  • looks beter, but I think you want `l[-1]` (i.e. the last list element) instead of `l[1:]` since the OP wrote "(only last elements of each list) will be concatenated to one new list". – Frerich Raabe Dec 02 '13 at 08:25
  • I was assuming the `...` referred to the possibility that the lists of lists included more than one element (though the example doesn't show it dealing with this possibility. – Jason Sperske Dec 02 '13 at 08:27