-1

I have a main List to store different lists that could be added at any time to main List. The problem I have is to delete the same values from the lists in the main list. So for example:

Initial List of lists:

[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q'),
  ('diamond', 'r')], [('not', 'p'), 'q'], ['p', 'q'], ['q', 'q'],
 ['r', 'q']]

Desired return:

[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q'),
  ('diamond', 'r')], [('not', 'p'), 'q'], ['p', 'q'], ['q'], ['r', 'q']]

Second example

Initial:

[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q'),
  ('diamond', 'q')], [('not', 'p'), 'q'], ['p', 'q'], ['q', 'q'],
 [('not', r'), 'q']]

return

[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q')],
 [('not', 'p'), 'q'], ['p', 'q'], ['q'], [('not', r'), 'q']]

Importantly, order must be the same and only the list inside the main list need not to have duplicates. I have seen many suggestions on stack overflow but none of them work because checking element by element would just leave me with 'diamond' or 'box' values on its own. Where in fact I need ('diamond','q') tuple to be added in full. This question is different to similar questions because I want to sort a single list inside the main list.

marcincuber
  • 3,451
  • 1
  • 17
  • 29
  • I would try using `set`. e.g `initial_list = [['foo',], ['bar', 'bar'], ['baz', ('foobar', 'barfoo')]]` and then `non_dupe_list = [set(x) for x in initial_list]` Does the order of the items in the sublists matter? – zsoobhan Oct 29 '15 at 00:23
  • Possible duplicate of [Python removing duplicates in lists](http://stackoverflow.com/questions/7961363/python-removing-duplicates-in-lists) – Leb Oct 29 '15 at 00:59

2 Answers2

6
from collections import OrderedDict

init_list = [[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q'), ('diamond', 'q')], [('not', 'p'), 'q'], ['p', 'q'], ['q', 'q'], [('not', 'r'), 'q']]

uniq_list = [list(OrderedDict.fromkeys(l)) for l in init_list]

OrderedDict allows you to create an ordered set since OrderedDict.fromkeys(l) returns a dictionary with keys from l preserving their order (and eliminating duplicates). list(OrderedDict) simply returns the dict's keys as a list.

sirfz
  • 4,097
  • 23
  • 37
  • Minor typo in import `from collections import OrderedDict`. Damn good idea with the OrderedDict. – zsoobhan Oct 29 '15 at 00:28
  • this is what I was looking for, however would it be possible to extend it a little bit and if we have ('not', 'p') and ('p') in the same sub list, I would like to print something? – marcincuber Oct 29 '15 at 20:44
  • @aki that's beyond the scope of your original question. You should create a new question for that IMO. – sirfz Oct 30 '15 at 20:39
0

You can use this recipe for an OrderedSet and then

init_list = # your list of lists
uniq_list = [list(OrderedSet(l)) for l in init_list]
gt6989b
  • 4,125
  • 8
  • 46
  • 64