Python Program to Filter Rows with a specific Pair Sum


When it is required to filter rows with a specific pair sum, a method is defined. It checks to see if elements in a specific index is equal to key, and returns output based on this.

Below is a demonstration of the same −

Example

 Live Demo

def find_sum_pair(val, key):

   for index in range(len(val)):
      for ix in range(index + 1, len(val)):
         if val[index] + val[ix] == key:
            return True
   return False

my_list = [[71, 5, 21, 6], [34, 21, 2, 71], [21, 2, 34, 5], [6, 9, 21, 42]]

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

my_key = 76
print("The key is ")
print(my_key)

my_result = [element for element in my_list if find_sum_pair(element, my_key)]

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

Output

The list is :
[[71, 5, 21, 6], [34, 21, 2, 71], [21, 2, 34, 5], [6, 9, 21, 42]]
The key is
76
The resultant list is :
[[71, 5, 21, 6]]

Explanation

  • A method named 'find_sum_pair' is defined that takes two parameters.

  • It iterates through the first parameter, and checks to see if elements in sum of values in two specific indices are equal to the second parameter.

  • If yes, the 'True' value is returned.

  • Otherwise, 'False' is returned.

  • Outside the method, a list of list is defined and is displayed on the console.

  • A value for key is defined.

  • The list comprehension is used to iterate over the list and the method is called by passing the required parameters.

  • This is assigned to a variable.

  • It is displayed as output on the console.

Updated on: 04-Sep-2021

140 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements