Suppose that I have a list of lists, e.g.
example_list = [[0, 0], [0, 1], [0, 1], [5, 4]]
I want a reasonably fast method of obtaining a list formed exclusively of elements that appear at least twice in the original list. In this example, the new list would be
new_list = [[0, 1]]
since [0, 1] is the only duplicate entry. I have spent lots of time on Stackoverflow looking for a solution, but none of them seem to work for me (details below). How should I proceed in this instance?
Unsuccessful attempts. One solution which does work is to write something like
new_list = [x for x in example_list if example_list.count(x) > 1]
However, this is too slow for my purposes.
Another solution (suggested here) is to write
totals = {}
for k,v in example_list:
totals[k] = totals.get(k,0) + v
totals.items()
[list(t) for t in totals.items()]
print(totals)
I may have misunderstood what the author is suggesting, but this doesn't work for me at all: it prints {0: 2, 5: 4}
in the terminal.
A final solution (also suggested on this page) is import Counter from collections and write
new_list = Counter(x for x, new_list in example_list for _ in xrange(new_list))
map(list, new_list.iteritems())
This flags an error on xrange and iteritems (I think it's a Python3 thing?), so I tried
new_list = Counter(x for x, new_list in example_list for _ in range(new_list))
map(list, new_list.items())
which yielded Counter({5: 4, 0: 2})
(again!!), which is of course not what I am after...