2015-03-25 9 views
6

Ho provato a utilizzare il metodo set() di python per trovare gli elementi univoci nell'elenco. Funziona bene rimuovendo tutti i duplicati. Ma ecco il mio requisito, voglio ottenere gli elementi che vengono rimossi utilizzando il metodo set(). Qualcuno potrebbe aiutarmi per favore in questo?Come identificare gli elementi che vengono rimossi da set() in python?

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

mio risultato atteso è [1] elemento .Il che viene rimosso dal set() metodo

+2

Che cosa succede se l'ingresso è '[1,2,3,1,4, 1, 1]'? – thefourtheye

+3

Prendi il conteggio e controlla gli articoli con conteggio> 1. –

risposta

1

È possibile estendere Set classe (avere la propria classe Set dire MySet) e sovrascrivere questa funzione

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 
+0

quindi la tua risposta è fondamentalmente "cambia qualcosa in queste 35 righe di codice"? ... – shx2

+0

Sì perché è quello che la domanda era. Per coloro che hanno usato Counter credo che tu abbia dato un'alternativa piuttosto che rispondere a quello che è stato chiesto (con cicli extra ecc.) Grazie per il voto negativo tra due :) –

2

collections.Counter è utile qui.

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

Non hai nemmeno bisogno di impostare. Vuoi un conteggio di ogni elemento con più di un'occorrenza. Contro dalle raccolte insieme a una comprensione del dizionario dovrebbe portarti lì.

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} 
1

Ciò restituirà un set che contiene solo gli elementi rimossi dal set originale:

>>> a = [1, 2, 3, 4, 1, 1, 5] 

>>> set(i for i in a if a.count(i) > 1) 

>>> {1} 
1

Penso che ti stai avvicinando al problema in modo leggermente conflittuale. Piuttosto che cercare di ottenere un set() per fare qualcosa che non è destinato a fare (restituire un elenco di duplicati) vorrei usare un collections.Counter() per raccogliere i duplicati e quindi ottenere il set da quello.

Ecco po 'di codice:

#!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()) 
2

Prova questa con Counter

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