Python | Уникальные значения в матрице

Опубликовано: 19 Марта, 2022

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

Method #1 : Using set() + list comprehension
The set function can be used to convert the individual list to a non-repeating element list and the list comprehension is used to iterate to each of the lists.

# Python3 code to demonstrate
# checking unique values in matrix
# set() + list comprehension
  
# initializing matrix 
test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
  
# printing the original matrix
print ("The original matrix is : " + str(test_matrix))
  
# using set() + list comprehension
# for checking unique values in matrix
res = list(set(i for j in test_matrix for i in j))
  
# printing result
print ("Unique values in matrix are : " + str(res))
Output:
The original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]

 
Method #2 : Using chain() + set()
The chain function performs the similar task that a list comprehension performs but in a faster way as it uses iterators for its internal processing and hence faster.

# Python3 code to demonstrate
# checking unique values in matrix
# chain() + set()
from itertools import chain
  
# initializing matrix 
test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
  
# printing the original matrix
print ("The original matrix is : " + str(test_matrix))
  
# using chain() + set()
# for checking unique values in matrix
res = list(set(chain(*test_matrix)))
  
# printing result
print ("Unique values in matrix are : " + str(res))
Output:
The original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.