How to identify elements that are removed from set () in python?

I tried using the set() method for python to find unique elements in a List. It works great by removing all duplicates. But here is my requirement, I want to get elements that are deleted using the set() method. Can someone help me with this?

 a=[1,2,3,1,4] b=set(a) Output:[1,2,3,4] 

My expected result [1] . The element that is removed from the set() method

+6
source share
6 answers

You can extend the Set class (have your own Set say MySet class) and override this function

 def _update(self, iterable): # The main loop for update() and the subclass __init__() methods. data = self._data # Use the fast update() method when a dictionary is available. if isinstance(iterable, BaseSet): data.update(iterable._data) return value = True if type(iterable) in (list, tuple, xrange): # Optimized: we know that __iter__() and next() can't # raise TypeError, so we can move 'try:' out of the loop. it = iter(iterable) while True: try: for element in it: data[element] = value return except TypeError: transform = getattr(element, "__as_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught data[transform()] = value else: # Safe: only catch TypeError where intended for element in iterable: try: data[element] = value except TypeError: transform = getattr(element, "__as_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught data[transform()] = value 
+1
source

collections.Counter is useful here.

 from collections import Counter counts = Counter(a) b = set(counts.keys()) for x, count in counts.items(): if count > 1: print('%d appearances of %s were removed in the set' % (count-1, x)) 
+2
source

You do not even need to install. You want to count every element with more than one occurrence. A collection counter along with dictionary knowledge should get you there.

 from collections import Counter a = [1, 1, 1, 2, 2, 3, 4] removed = {k: v-1 for k, v in Counter(a).iteritems() if v > 1} >>> removed Out[8]: {1: 2, 2: 1} 
+2
source

Try it with Counter

 from collections import Counter a = [1, 2, 3, 1, 4] >>>[i for i in Counter(a) if Counter(a)[i] > 1] [1] 
+2
source

This will return a collection containing only items removed from the original collection:

 >>> a = [1, 2, 3, 4, 1, 1, 5] >>> set(i for i in a if a.count(i) > 1) >>> {1} 
+1
source

I think you are a little closer to the problem. Instead of trying to get set() to do something that he was not going to do (return a list of duplicates), I would use collections.Counter() to collect duplicates, and then get the set from that.

Here is the code:

 #!python from collections import Counter c = Counter([1,2,3,1,4]) dupes = [k for k,v in c.items() if v>1] b = set(c.keys()) 
+1
source

Source: https://habr.com/ru/post/984224/


All Articles