- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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)
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]]
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.
- Python Program to print a specific number of rows with Maximum Sum
- Python - Sum only specific rows of a Pandas Dataframe
- Python – Filter rows with required elements
- Python – Filter Rows with Range Elements
- Python – Filter Sorted Rows
- Python – Filter Tuples with Strings of specific characters
- Filter the rows – Python Pandas
- Find pairs with given sum such that elements of pair are in different rows in Python
- Python – Filter rows with Elements as Multiple of K
- How can Tensorflow be used to sum specific elements/rows of a matrix in Python?
- MySQL query to count rows with a specific column?
- Python – Filter rows without Space Strings
- How to filter a query on specific date format with MongoDB?
- Python – Filter rows with only Alphabets from List of Lists