Python only unique elements in array

Как получить уникальные элементы списка python

Предположим, есть список, который содержит повторяющиеся числа:

Но нужен список с уникальными числами:

Есть несколько вариантов, как можно получить уникальные значения. Разберем их.

Вариант №1. Использование множества (set) для получения элементов

Использование множества ( set ) — один из вариантов. Он удобен тем, что включает только уникальные элементы. После этого множество можно обратно превратить в список.

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

 
numbers = [1, 2, 2, 3, 3, 4, 5]

def get_unique_numbers(numbers):
list_of_unique_numbers = []
unique_numbers = set(numbers)

for number in unique_numbers:
list_of_unique_numbers.append(number)

return list_of_unique_numbers

print(get_unique_numbers(numbers))

Разберем, что происходит на каждом этапе. Есть список чисел numbers . Передаем его в функцию get_unique_numbers .

Внутри этой функции создается пустой список, который в итоге будет включать все уникальные числа. После этого используется set для получения уникальных чисел из списка numbers .

 
unique_numbers = set(numbers)

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

 
for number in unique_numbers:
list_of_unique_numbers.append(number)

На каждой итерации текущее число добавляется в список list_of_unique_numbers . Наконец, именно этот список возвращается в конце программы.

Есть и более короткий способ использования множества для получения уникальных значений в Python. О нем и пойдет речь дальше.

Короткий вариант с set

Весь код выше можно сжать в одну строку с помощью встроенных в Python функций.

 
numbers = [1, 2, 2, 3, 3, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers)

Хотя этот код сильно отличается от первого примера, идея та же. Сперва множество используется для получения уникальных значений. После этого множество превращается в список.

 
unique_numbers = list(set(numbers))

Проще всего думать «изнутри наружу» при чтении этого кода. Самый вложенный код выполняется первым: set(numbers) . Затем — внешний блок: list(set(numbers)) .

Вариант №2. Использование цикла for

Также стоит рассмотреть подход с использованием цикла.

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

Рассмотрим два способа использования цикла. Начнем с более подробного.

 
numbers = [20, 20, 30, 30, 40]

def get_unique_numbers(numbers):
unique = []

for number in numbers:
if number in unique:
continue
else:
unique.append(number)
return unique

print(get_unique_numbers(numbers))

Вот что происходит на каждом этапе. Сначала есть список чисел numbers . Он передается в функцию get_unique_numbers .

Внутри этой функции создается пустой список unique . В итоге он будет включать все уникальные значения.

Цикл будет использоваться для перебора по числам в списке numbers .

 
for number in numbers:
if number in unique:
continue
else:
unique.append(number)

Условные конструкции в цикле проверяют, есть ли число текущей итерации в списке unique . Если да, то цикл переходит на следующую итерации. Если нет — число добавляется в список.

Важно отметить, что добавляются только уникальные числа. Когда цикл завершен, список unique с уникальными числами возвращается.

Короткий способ с циклом

Есть и другой способ использования варианта с циклом, который короче на несколько строк.

 
numbers = [20, 20, 30, 30, 40]

def get_unique_numbers(numbers):
unique = []
for number in numbers:
if number not in unique:
unique.append(number)
return unique

Разница в условной конструкции. В этот раз она следующая — если числа нет в unique , то его нужно добавить.

 
if number not in unique:
unique.append(number)

В противном случае цикл перейдет к следующему числу в списке numbers .

Результат будет тот же. Но иногда подобное читать сложнее, когда булево значение опускается.

Есть еще несколько способов поиска уникальных значений в списке Python. Но достаточно будет тех, которые описаны в этой статье.

Обучение с трудоустройством

Я создал этот блог в 2018 году, чтобы распространять полезные учебные материалы, документации и уроки на русском. На сайте опубликовано множество статей по основам python и библиотекам, уроков для начинающих и примеров написания программ.

Python Q CEO Pythonru admin@pythonru.com https://secure.gravatar.com/avatar/b16f253879f7349f64830c64d1da4415?s=96&d=mm&r=g CEO Pythonru Python Александр Редактор https://t.me/cashncarryhttps://pythonru.com/https://yandex.ru/q/profile/cashnc/ PythonRu.com admin@pythonru.com Alex Zabrodin 2018-10-26 Online Python, Programming, HTML, CSS, JavaScript

Источник

Python Unique List – How to Get all the Unique Values in a List or Array

Amy Haddad

Amy Haddad

Python Unique List – How to Get all the Unique Values in a List or Array

Say you have a list that contains duplicate numbers:

But you want a list of unique numbers.

There are a few ways to get a list of unique values in Python. This article will show you how.

Option 1 – Using a Set to Get Unique Elements

Using a set one way to go about it. A set is useful because it contains unique elements.

You can use a set to get the unique elements. Then, turn the set into a list.

Let’s look at two approaches that use a set and a list. The first approach is verbose, but it’s useful to see what’s happening each step of the way.

numbers = [1, 2, 2, 3, 3, 4, 5] def get_unique_numbers(numbers): list_of_unique_numbers = [] unique_numbers = set(numbers) for number in unique_numbers: list_of_unique_numbers.append(number) return list_of_unique_numbers print(get_unique_numbers(numbers)) # result: [1, 2, 3, 4, 5] 

Let’s take a closer look at what’s happening. I’m given a list of numbers, numbers . I pass this list into the function, get_unique_numbers .

Inside the function, I create an empty list, which will eventually hold all of the unique numbers. Then, I use a set to get the unique numbers from the numbers list.

unique_numbers = set(numbers) 

I have what I need: the unique numbers. Now I need to get these values into a list. To do so, I use a for loop to iterate through each number in the set.

for number in unique_numbers: list_of_unique_numbers.append(number) 

On each iteration I add the current number to the list, list_of_unique_numbers . Finally, I return this list at the end of the program.

There’s a shorter way to use a set and list to get unique values in Python. That’s what we’ll tackle next.

A Shorter Approach with Set

All of the code written in the above example can be condensed into one line with the help of Python’s built-in functions.

numbers = [1, 2, 2, 3, 3, 4, 5] unique_numbers = list(set(numbers)) print(unique_numbers) # Result: [1, 2, 3, 4, 5] 

Although this code looks very different from the first example, the idea is the same. Use a set to get the unique numbers. Then, turn the set into a list.

unique_numbers = list(set(numbers)) 

It’s helpful to think “inside out” when reading the above code. The innermost code gets evaluated first: set(numbers) . Then, the outermost code is evaluated: list(set(numbers)) .

Option 2 – Using Iteration to Identify Unique Values

Iteration is another approach to consider.

The main idea is to create an empty list that’ll hold unique numbers. Then, use a for loop iterate over each number in the given list. If the number is already in the unique list, then continue on to the next iteration. Otherwise, add the number to it.

Let's look at two ways to use iteration to get the unique values in a list, starting with the more verbose one.

numbers = [20, 20, 30, 30, 40] def get_unique_numbers(numbers): unique = [] for number in numbers: if number in unique: continue else: unique.append(number) return unique print(get_unique_numbers(numbers)) # Result: [20, 30, 40] 

Here’s what’s happening each step of the way. First, I’m given a list of numbers, numbers . I pass this list into my function, get_unique_numbers .

Inside the function, I create an empty list, unique . Eventually, this list will hold all of the unique numbers.

I use a for loop to iterate through each number in the numbers list.

 for number in numbers: if number in unique: continue else: unique.append(number) 

The conditional inside the loop checks to see if the number of the current iteration is in the unique list. If so, the loop continues to the next iteration. Otherwise, the number gets added to this list.

Here’s the important point: only the unique numbers are added. Once the loop is complete, then I return unique which contains all of the unique numbers.

A Shorter Approach with Iteration

There’s another way to write the function in fewer lines.

numbers = [20, 20, 30, 30, 40] def get_unique_numbers(numbers): unique = [] for number in numbers: if number not in unique: unique.append(number) return unique #Result: [20, 30, 40] 

The difference is the conditional. This time it’s set up to read like this: if the number is not in unique , then add it.

if number not in unique: unique.append(number) 

Otherwise, the loop will move along to the next number in the list, numbers .

The result is the same. However, it’s sometimes harder to think about and read code when the boolean is negated.

There are other ways to find unique values in a Python list. But you’ll probably find yourself reaching for one of the approaches covered in this article.

I write about learning to program, and the best ways to go about it on amymhaddad.com. Follow me on Twitter: @amymhaddad.

Источник

Читайте также:  Название документа
Оцените статью