Python – Remove Rows for similar Kth column element

PythonServer Side ProgrammingProgramming

When it is required to remove rows for a similar ‘K’th column element, a simple iteration, and the ‘append’ method are used.

Example

Below is a demonstration of the same −

my_list = [[45, 95, 26], [70, 35, 74], [87, 65, 23], [70, 35, 74], [67,85,12], [45,65,0]]

print("The list is : " )
print(my_list)

K = 1
print("The value of K is ")
print(K)

my_result = []
my_mem = []
for index in my_list:

   if not index[K] in my_mem:
      my_result.append(index)
      my_mem.append(index[K])

print("The resultant list is : ")
print(my_result)

Output

The list is :
[[45, 95, 26], [70, 35, 74], [87, 65, 23], [70, 35, 74], [67, 85, 12], [45, 65, 0]]
The value of K is
1
The resultant list is :
[[45, 95, 26], [70, 35, 74], [87, 65, 23], [67, 85, 12]]

Explanation

  • A list of list is defined and is displayed on the console.

  • The value for K is initialized and is printed on the console.

  • Two empty lists are defined.

  • The original list is iterated over if a specific index is not found in the second list, the index is appended to first list, and the element at the index is appended to the second list.

  • The first list is displayed as the output on the console.

raja
Published on 13-Sep-2021 11:04:30
Advertisements