Python | Remove similar strings of elements in a Matrix tuple



Method # 1: Using List Comprehension + all()
This task can be accomplished using a combination of the above functions. In this, we loop through all the rows using a list comprehension and remove all elements that match the starting element in the row column with all () .

# Python3 code to demonstrate how it works
# Remove similar lines of elements in the Matrix tuple
# using list comprehension + all ()

 
# initialize the tuple

test_tup = (( 1 , 3 , 5 ), ( 2 , 2 , 2 ),

  ( 9 , 10 , 10 ), ( 4 , 4 , 4 ))

 
# printing the original tuple

print ( "The original tuple:" + str (test_tup))

  
# Remove similar lines of elements in the Matrix tuple
 # using list comprehension + all ()

res = tuple (ele for ele in test_tup if not all (sub = = ele [ 0 ] for sub in ele))

 
# print result

print ( "The tuple after removal of like-element rows:" + str (res))

Output:

 The original tuple: ((1, 3, 5), (2, 2, 2), (9, 10, 10), (4, 4, 4)) The tuple after removal of like-element rows: ((1, 3, 5), (9, 10, 10)) 

Method # 2: Using the set () + expression generator
This task can also be accomplished using the functions provided. In this, we simply check the length of the shortened string using set (), which is greater than 1. If so, we know that this is the target string to be removed.

# Python3 code to demonstrate how it works
# Remove similar lines of elements in the Matrix tuple
# using set () + expression generator

 
# initialize tuple

test_tup = (( 1 , 3 , 5 ), ( 2 , 2 ,   2 ), 

( 9 , 10 , 10 ), ( 4 , 4 , 4 ))

 
# print the original tuple

print ( "The original tuple:" + str (test_tup))

 
# Remove similar lines of elements in the Matrix tuple
# using set ( ) + expression generator

res = tuple (ele for ele in test_tup if len ( set (ele)) & gt;  1 )

 
# print result

print ( "The tuple after removal of like-element rows:" + str (res))

Exit:

 The original tuple: ((1, 3, 5), (2, 2, 2), (9, 10, 10), (4, 4, 4)) The tuple after removal of like-element rows: ((1, 3, 5), (9, 10, 10))