Python поиск уникальных значений

Изучаем Python: поиск в списке

В этой статье мы рассмотрим три способа получения уникальных значений из списка Python .

Способы получения уникальных значений из списка в Python

Уникальные значения из списка можно извлечь с помощью:

1. Set()

Поскольку список преобразуется в набор, в него помещается только одна копия всех элементов.

list_inp = [100, 75, 100, 20, 75, 12, 75, 25] set_res = set(list_inp) print("The unique elements of the input list using set():n") list_res = (list(set_res)) for item in list_res: print(item)
The unique elements of the input list using set(): 25 75 100 20 12

2. Python list.append() и цикл for

Чтобы найти уникальные элементы, используем цикл for вместе с функцией list.append().

  • Создадим новый список res_list.
  • С помощью цикла for проверяем наличие определенного элемента в созданном списке (res_list). Если элемент отсутствует, он добавляется в новый список с помощью метода append().

Если во время переборки мы сталкиваемся с элементом, который уже существует в новом списке, то он игнорируется циклом for. Используем оператор if, чтобы проверить, является ли элемент уникальным или копией.

list_inp = [100, 75, 100, 20, 75, 12, 75, 25] res_list = [] for item in list_inp: if item not in res_list: res_list.append(item) print("Unique elements of the list using append():n") for item in res_list: print(item)
Unique elements of the list using append(): 100 75 20 12 25

3. Метод numpy.unique() для создания списка с уникальными элементами

Модуль Python NumPy включает в себя встроенную функцию numpy.unique, предназначенную для извлечения уникальных элементов из массива.

Далее используем метод numpy.unique() для извлечения уникальных элементов данных из массива numpy.

numpy.unique(numpy-array-name)
import numpy as N list_inp = [100, 75, 100, 20, 75, 12, 75, 25] res = N.array(list_inp) unique_res = N.unique(res) print("Unique elements of the list using numpy.unique():n") print(unique_res)
Unique elements of the list using numpy.unique(): [12 20 25 75 100]

Заключение

В этой статье мы рассмотрели три способа извлечения уникальных значений из списка Python.

Читайте также:  Google maps for phone java

Вадим Дворников автор-переводчик статьи « Get Unique Values From a List in Python »

Пожалуйста, оставляйте свои мнения по текущей теме статьи. Мы крайне благодарны вам за ваши комментарии, подписки, дизлайки, отклики, лайки!

Источник

Получение уникальных значений из списка в Python

В этой статье мы рассмотрим 3 способа получения уникальных значений из списка в Python. Имея дело с огромным количеством необработанных данных, мы часто сталкиваемся с ситуациями, когда нам нужно извлечь уникальный и неповторяющийся набор данных из необработанного набора входных данных.

Для получения уникальных значений из списка в Python можно использовать любой из следующих способов:

  • Метод set();
  • Использование метода list.append() вместе с циклом for;
  • Использование метода Python numpy.unique().

Set() для получения уникальных значений из списка

Set хранит в себе одну копию повторяющихся значений. Это свойство можно использовать для получения уникальных значений из списка в Python.

  • Когда список преобразуется в набор, в него помещается только одна копия всех повторяющихся элементов.
  • Затем нам нужно будет преобразовать набор обратно в список, используя следующую команду:
list_inp = [100, 75, 100, 20, 75, 12, 75, 25] set_res = set(list_inp) print("The unique elements of the input list using set():\n") list_res = (list(set_res)) for item in list_res: print(item)
The unique elements of the input list using set(): 25 75 100 20 12

list.append() и цикл for

Чтобы найти уникальные элементы, мы можем применить цикл Python for вместе с функцией list.append(), чтобы добиться того же:

  • Сначала мы создаем новый (пустой) список, т.е. res_list.
  • После этого, используя цикл for, мы проверяем наличие определенного элемента в новом созданном списке (res_list). Если элемент отсутствует, он добавляется в новый список с помощью метода append().

В случае, если при обходе мы сталкиваемся с элементом, который уже существует в новом списке, то есть повторяющимся элементом, в этом случае он игнорируется циклом for. Мы будем использовать оператор if, чтобы проверить, является ли этот элемент уникальным или повторяющимся.

list_inp = [100, 75, 100, 20, 75, 12, 75, 25] res_list = [] for item in list_inp: if item not in res_list: res_list.append(item) print("Unique elements of the list using append():\n") for item in res_list: print(item)
Unique elements of the list using append(): 100 75 20 12 25

numpy.unique() для создания списка с уникальными элементами

Модуль NumPy имеет встроенную функцию с именем numpy.unique для извлечения уникальных элементов данных из массива numpy.

Читайте также:  Нейронная сеть персептрон python

Чтобы получить уникальные элементы из списка Python, нам нужно будет преобразовать список в массив NumPy, используя следующую команду.

Затем мы будем использовать метод numpy.unique() для извлечения уникальных элементов данных из массива numpy и, наконец, распечатаем получившийся список.

numpy.unique(numpy-array-name)
import numpy as N list_inp = [100, 75, 100, 20, 75, 12, 75, 25] res = N.array(list_inp) unique_res = N.unique(res) print("Unique elements of the list using numpy.unique():\n") print(unique_res)
Unique elements of the list using numpy.unique(): [12 20 25 75 100]

Источник

Get Unique Values From a List in Python

Get Unique Values From a List in Python

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

In this article, we will be understanding 3 ways to get unique values from a Python list. While dealing with a huge amount of raw data, we often come across situations wherein we need to fetch out the unique and non-repeated set of data from the raw input data-set. The methods listed below will help you solve this problem. Let’s get right into it!

Ways to Get Unique Values from a List in Python

  • Python set() method
  • Using Python list.append() method along with a for loop
  • Using Python numpy.unique() method

1. Python Set() to Get Unique Values from a List

As seen in our previous tutorial on Python Set, we know that Set stores a single copy of the duplicate values into it. This property of set can be used to get unique values from a list in Python.

  • As the list gets converted to set, only a single copy of all the duplicate elements gets placed into it.
  • Then, we will have to convert the set back to the list using the below command/statement:
list_inp = [100, 75, 100, 20, 75, 12, 75, 25] set_res = set(list_inp) print("The unique elements of the input list using set():\n") list_res = (list(set_res)) for item in list_res: print(item) 
The unique elements of the input list using set(): 25 75 100 20 12 

2. Python list.append() and for loop

In order to find the unique elements, we can apply a Python for loop along with list.append() function to achieve the same.

  • At first, we create a new (empty) list i.e res_list.
  • After this, using a for loop we check for the presence of a particular element in the new list created (res_list). If the element is not present, it gets added to the new list using the append() method.
  • In case, we come across an element while traversing that already exists in the new list i.e. a duplicate element, in such case it is neglected by the for loop. We will use the if statement to check whether it’s a unique element or a duplicate one.
list_inp = [100, 75, 100, 20, 75, 12, 75, 25] res_list = [] for item in list_inp: if item not in res_list: res_list.append(item) print("Unique elements of the list using append():\n") for item in res_list: print(item) 
Unique elements of the list using append(): 100 75 20 12 25 

3. Python numpy.unique() function To Create a List with Unique Items

Python NumPy module has a built-in function named, numpy.unique to fetch unique data items from a numpy array.

  • In order to get unique elements from a Python list, we will need to convert the list to NumPy array using the below command:
  • Next, we will use the numpy.unique() method to fetch the unique data items from the numpy array
  • and finally, we’ll print the resulting list.
numpy.unique(numpy-array-name) 
import numpy as N list_inp = [100, 75, 100, 20, 75, 12, 75, 25] res = N.array(list_inp) unique_res = N.unique(res) print("Unique elements of the list using numpy.unique():\n") print(unique_res) 
Unique elements of the list using numpy.unique(): [12 20 25 75 100] 

Conclusion

In this article, we have unveiled various ways to fetch the unique values from a set of data items in a Python list.

Читайте также:  Progress bar php cli

References

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью