Python – Sposoby usuwania duplikatów z listy
W tym artykule skupiono się na jednej z operacji uzyskiwania unikalnej listy z listy zawierającej możliwy duplikat. Usuwanie duplikatów z operacji listowych ma wiele zastosowań, dlatego warto posiadać jego wiedzę Pyton.
Sposoby usuwania duplikatów z listy:
Poniżej znajdują się metody, które omówimy w tym artykule:
- Za pomocą metoda set().
- Za pomocą zrozumienie listy
- Używanie rozumienia list z wyliczać()
- Za pomocą kolekcje.ZamówioneDict.fromkeys()
- Używanie w, nie w operatorzy
- Za pomocą zrozumienie listy oraz metodę Array.index().
- Za pomocą Metoda licznika().
- Za pomocą Numpy, unikalna metoda
- Używać Ramka danych Pandy
Usuń duplikaty z listy za pomocą metody set().
Jest to najpopularniejszy sposób usuwania duplikatów z listy metoda set(). . Jednak główną i zauważalną wadą tego podejścia jest to, że w tej konkretnej metodzie tracona jest kolejność elementów.
Python3
# initializing list> test_list> => [> 1> ,> 5> ,> 3> ,> 6> ,> 3> ,> 5> ,> 6> ,> 1> ]> print> (> 'The original list is : '> > +> str> (test_list))> # using set() to remove duplicated from list> test_list> => list> (> set> (test_list))> # printing list after removal> # distorted ordering> print> (> 'The list after removing duplicates : '> > +> str> (test_list))> |
Wyjście
The original list is : [1, 5, 3, 6, 3, 5, 6, 1] The list after removing duplicates : [1, 3, 5, 6]
Złożoność czasowa: NA)
Złożoność przestrzeni: NA)
Usuń duplikaty z listy, korzystając ze zrozumienia list
Ta metoda działa podobnie do powyższej metody, ale jest to tylko jednowierszowy skrót dłuższej metody wykonywanej za pomocą zrozumienie listy. zamówienie
Python3
# initializing list> test_list> => [> 1> ,> 3> ,> 5> ,> 6> ,> 3> ,> 5> ,> 6> ,> 1> ]> print> (> 'The original list is : '> > +> str> (test_list))> # using list comprehension to remove duplicated from list> res> => []> [res.append(x)> for> x> in> test_list> if> x> not> in> res]> # printing list after removal> print> (> 'The list after removing duplicates : '> > +> str> (res))> |
Wyjście
The original list is : [1, 3, 5, 6, 3, 5, 6, 1] The list after removing duplicates : [1, 3, 5, 6]
Złożoność czasowa: NA)
Złożoność przestrzeni: NA)
Usuń duplikaty z listy, używając rozumienia list za pomocą enumerate()
The zrozumienie listy w połączeniu z wyliczyć funkcję może również sprostać temu zadaniu. Zasadniczo szuka już istniejących elementów i pomija ich dodawanie. Zachowuje kolejność listy.
Python3
# initializing list> test_list> => [> 1> ,> 5> ,> 3> ,> 6> ,> 3> ,> 5> ,> 6> ,> 1> ]> print> (> 'The original list is : '> > +> str> (test_list))> # using list comprehension + enumerate() to remove duplicated from list> res> => [i> for> n, i> in> enumerate> (test_list)> if> i> not> in> test_list[:n]]> # printing list after removal> print> (> 'The list after removing duplicates : '> > +> str> (res))> |
Wyjście
The original list is : [1, 5, 3, 6, 3, 5, 6, 1] The list after removing duplicates : [1, 5, 3, 6]
Złożoność czasowa: O(n^2)
Złożoność przestrzeni: NA)
Usuń duplikaty z listy w Pythonie za pomocą kolekcji.OrderedDict.fromkeys()
Jest to najszybsza metoda osiągnięcia określonego zadania. Najpierw usuwa duplikaty i zwraca słownik, który należy przekonwertować na listę. Działa to również dobrze w przypadku ciągów.
Python3
# using collections.OrderedDict.fromkeys()> from> collections> import> OrderedDict> # initializing list> test_list> => [> 1> ,> 5> ,> 3> ,> 6> ,> 3> ,> 5> ,> 6> ,> 1> ]> print> (> 'The original list is : '> > +> str> (test_list))> # using collections.OrderedDict.fromkeys() to remove duplicated from list> res> => list> (OrderedDict.fromkeys(test_list))> # printing list after removal> print> (> 'The list after removing duplicates : '> > +> str> (res))> |
Wyjście
The original list is : [1, 5, 3, 6, 3, 5, 6, 1] The list after removing duplicates : [1, 5, 3, 6]
Złożoność czasowa: NA)
Złożoność przestrzeni: NA)
Usuń duplikaty z listy, używając operatorów in, a nie in
W tym przypadku iterujemy po liście i utrzymujemy z nią odpowiednią listę, która zawiera element listy wejściowej, a przed dodaniem nowego elementu do odpowiedniej listy sprawdzamy, czy element już istnieje na odpowiedniej liście, czy nie i w ten sposób możemy usunąć duplikat listy wejściowej.
Python3
# initializing list> test_list> => [> 1> ,> 5> ,> 3> ,> 6> ,> 3> ,> 5> ,> 6> ,> 1> ]> print> (> 'The original list is : '> +> str> (test_list))> res> => []> for> i> in> test_list:> > if> i> not> in> res:> > res.append(i)> # printing list after removal> print> (> 'The list after removing duplicates : '> +> str> (res))> |
Wyjście
The original list is : [1, 5, 3, 6, 3, 5, 6, 1] The list after removing duplicates : [1, 5, 3, 6]
Złożoność czasowa: O(n^2)
Złożoność przestrzeni: NA)
Usuń duplikaty z listy za pomocą zrozumienie list i metoda Array.index().
W tej metodzie używamy rozumienia list do iteracji po indeksowaniu listy i tablicy w celu pobrania elementu z tablicy. Dodajemy elementy do tablicy tylko wtedy, gdy pierwszy indeks elementu w tablicy odpowiada bieżącemu indeksowi elementu lub w przeciwnym razie element jest zaniedbywany.
Pyton
# initializing list> arr> => [> 1> ,> 5> ,> 3> ,> 6> ,> 3> ,> 5> ,> 6> ,> 1> ]> print> (> 'The original list is : '> +> str> (arr))> # using list comprehension + arr.index()> res> => [arr[i]> for> i> in> range> (> len> (arr))> if> i> => => arr.index(arr[i]) ]> # printing list after removal of duplicate> print> (> 'The list after removing duplicates :'> > ,res)> |
Wyjście
The original list is : [1, 5, 3, 6, 3, 5, 6, 1] ('The list after removing duplicates :', [1, 5, 3, 6]) Złożoność czasowa: O(n^2)
Złożoność przestrzeni: NA)
Usuń duplikaty z listy za pomocą Lub Metoda licznika().
W tej metodzie używamy Metoda licznika(). aby utworzyć słownik z danej tablicy. Teraz odzyskaj wszystkie klucze za pomocą Klucze() metoda, która daje tylko unikalne wartości z poprzedniej listy.
Python3
from> collections> import> Counter> # initializing list> arr> => [> 1> ,> 5> ,> 3> ,> 6> ,> 3> ,> 5> ,> 6> ,> 1> ]> print> (> 'The original list is : '> +> str> (arr))> # using Counter() + keys() to remove duplicated from list> temp> => Counter(arr)> res> => [> *> temp]> # printing list after removal of duplicate> print> (> 'The list after removing duplicates :'> > ,res)> |
Wyjście
The original list is : [1, 5, 3, 6, 3, 5, 6, 1] The list after removing duplicates : [1, 5, 3, 6]
Złożoność czasowa: NA)
Złożoność przestrzeni: NA)
Usuń duplikaty z listy za pomocą unikalnej metody numpy
Metodę tę stosuje się, gdy lista zawiera elementy tego samego typu i służy do usuwania duplikatów z listy. Najpierw konwertuje listę na plik a tablica numpy a następnie używa metoda numpy unikalna(). aby usunąć wszystkie zduplikowane elementy z listy.
Uwaga: Zainstaluj moduł numpy za pomocą polecenia pip install numpy duplikować
Python3
# initializing list> test_list> => [> 1> ,> 5> ,> 3> ,> 6> ,> 3> ,> 5> ,> 6> ,> 1> ]> print> (> 'The original list is : '> > +> str> (test_list))> > # using numpy> import> numpy as np> > # removing duplicated from list> res> => np.unique(test_list)> > # printing list after removal> print> (> 'The list after removing duplicates : '> > +> str> (res))> |
Wyjście
The original list is : [1, 5, 3, 6, 3, 5, 6, 1] The list after removing duplicates : [1 3 5 6]
Złożoność czasowa: NA)
Złożoność przestrzeni: NA)
Korzystanie z ramki danych pand
The pandy.DataFrame.drop_duplicates() metody można również użyć do usunięcia duplikatów z listy. Metoda zwraca nową ramkę DataFrame z usuniętymi duplikatami oraz oryginalne dane ramki danych rama pozostaje bez zmian.
Algorytm:
Utwórz ramkę danych pandy z listą. Użyj metody drop_duplicates() na ramce DataFram, a następnie przekonwertuj wynikową ramkę DataFrame na listę.
Python3
import> pandas as pd> # initializing list> test_list> => [> 1> ,> 5> ,> 3> ,> 6> ,> 3> ,> 5> ,> 6> ,> 1> ]> print> (> 'The original list is : '> +> str> (test_list))> # creating DataFrame> df> => pd.DataFrame({> 'col'> : test_list})> # using drop_duplicates() method> df.drop_duplicates(inplace> => True> )> # converting back to list> res> => df[> 'col'> ].tolist()> # printing list after removal> print> (> 'The list after removing duplicates : '> +> str> (res))> |
Wyjście:
The original list is : [1, 5, 3, 6, 3, 5, 6, 1] The list after removing duplicates : [1 , 5 , 3, 6]
Złożoność czasowa: Złożoność czasowa metody drop_duplicates() wynosi O(n log n), ponieważ sortuje ona wartości przed usunięciem duplikatów. Konwersja z DataFrame na listę zajmuje czas O(n). Dlatego całkowita złożoność czasowa tej metody wynosi O (n log n).
Złożoność przestrzeni: Złożoność przestrzenna tej metody wynosi O(n), ponieważ tworzona jest nowa ramka DataFrame i lista, każda zawierająca n elementów.