Open In App

Python | Selective Records Value Summation

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while using a list of tuples, we come across a problem in which we have e certain list of keys and we just need the summation of values of those keys from the list of tuples. This has a utility in rating or summation of specific entities. Let’s discuss certain ways in which this can be done. 

Method #1: Using dict() + sum() + get() + list comprehension We can perform this particular task by first, converting the list into the dictionary and then employing list comprehension to get the value of specific keys using g get to function. The summation of values is performed using sum(). 

Python3




# Python3 code to demonstrate
# Selective Records Value Summation
# using dict() + get() + list comprehension + sum()
 
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
 
# initializing selection list
select_list = ['Nikhil', 'Akshat']
 
# printing original list
print("The original list is : " + str(test_list))
 
# printing selection list
print("The selection list is : " + str(select_list))
 
# using dict() + get() + list comprehension + sum()
# Selective Records Value Summation
temp = dict(test_list)
res = sum([temp.get(i, 0) for i in select_list])
 
# printing result
print("The selective values summation of keys : " + str(res))


Output

The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values summation of keys : 4

Time complexity: O(n) where n is the number of elements in the test_list.
Auxiliary space: O(n) for storing the elements in the dictionary.

Method #2: Using next() + sum() + list comprehension This particular problem can be solved using the next function which performs the iteration using the iterators and hence the more efficient way to achieve a possible solution. The summation of values is performed using sum(). 

Python3




# Python3 code to demonstrate
# Selective Records Value Summation
# using next() + list comprehension + sum()
 
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
 
# initializing selection list
select_list = ['Nikhil', 'Akshat']
 
# printing original list
print("The original list is : " + str(test_list))
 
# printing selection list
print("The selection list is : " + str(select_list))
 
# using next() + list comprehension + sum()
# Selective Records Value Summation
res = sum([next((sub[1] for sub in test_list if sub[0] == i), 0)
           for i in select_list])
 
# printing result
print('The selective values summation of keys : ' + str(res))


Output

The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values summation of keys : 4

Time Complexity: O(n) where n is the length of test_list
Auxiliary Space: O(n) where n is the length of select_list

Method #3 : Using next() + sum() + list comprehension

Python3




# Python3 code to demonstrate
# Selective Records Value Summation
 
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
 
# initializing selection list
select_list = ['Nikhil', 'Akshat']
 
# printing original list
print("The original list is : " + str(test_list))
 
# printing selection list
print("The selection list is : " + str(select_list))
res = 0
for i in test_list:
    if i[0] in select_list:
        res += i[1]
 
 
# printing result
print("The selective values summation of keys : " + str(res))


Output

The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values summation of keys : 4

Time complexity: O(n) where n is the number of elements in test_list 
Auxiliary space: O(1).

Method #3B: Using for loop and sum() method

Python3




# Python3 code to demonstrate
# Selective Records Value Summation
 
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
 
# initializing selection list
select_list = ['Nikhil', 'Akshat']
 
# printing original list
print("The original list is : " + str(test_list))
 
# printing selection list
print("The selection list is : " + str(select_list))
x=[]
for i in test_list:
    if i[0] in select_list:
        x.append(i[1])
res=sum(x)
 
 
# printing result
print("The selective values summation of keys : " + str(res))


Output

The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values summation of keys : 4

Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(m), where m is the number of elements in the selection list select_list. 

Method#4: Using Recursive method.

  1. Define the function selective_sum with two parameters test_list and select_list.
  2. Check if the test_list is empty. If it is empty, return 0.
  3. Check if the key of the first tuple in the test_list is in the select_list. If it is, add its value to the result and call the function recursively with the rest of the list and the same select_list. If it is not, just call the function recursively with the rest of the list and the same select_list.
  4. Return the result.

Python3




def selective_sum(test_list, select_list):
    if not test_list:
        return 0
    elif test_list[0][0] in select_list:
        return test_list[0][1] + selective_sum(test_list[1:], select_list)
    else:
        return selective_sum(test_list[1:], select_list)
 
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
 
# initializing selection list
select_list = ['Nikhil', 'Akshat']
 
# printing original list
print("The original list is : " + str(test_list))
 
# printing selection list
print("The selection list is : " + str(select_list))
 
res= selective_sum(test_list, select_list)
 
# printing result
print("The selective values summation of keys : " + str(res))
#this code contributed by tvsk


Output

The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values summation of keys : 4

Time complexity: O(n), where n is the length of the input list, because the function needs to iterate through each element of the list exactly once.
Auxiliary space: O(n), because the function needs to create a new call stack frame for each recursive call, and there will be n total recursive calls (assuming all the elements in the list are selected). However, the space used by the function is proportional to the depth of the recursive calls, which in this case is also n, so the overall space complexity is O(n).

Method 5 : Using a loop to iterate over the list of tuples and check if the first element of each tuple is in the selection list. If it is, add the second element to a running total.

This approach uses a loop to iterate over the list of tuples and check if the first element of each tuple is in the selection list. If it is, it adds the second element of the tuple to a running total. Finally, it returns the total.

Python3




# Python3 code to demonstrate
# Selective Records Value Summation
# using for loop
 
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
 
# initializing selection list
select_list = ['Nikhil', 'Akshat']
 
# printing original list
print("The original list is : " + str(test_list))
 
# printing selection list
print("The selection list is : " + str(select_list))
 
# using for loop
# Selective Records Value Summation
total = 0
for tup in test_list:
    if tup[0] in select_list:
        total += tup[1]
 
# printing result
print("The selective values summation of keys : " + str(total))


Output

The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values summation of keys : 4

Time complexity of the above code is O(n), where n is the number of tuples in the input list. The loop iterates over the entire input list once.
Auxiliary space complexity is O(1), as we only use a constant amount of extra space to keep track of the running total.

Method 6: Using pandas library

We can use the pandas library to convert the list of tuples into a pandas DataFrame, then filter the DataFrame based on the selection list, and finally calculate the summation of the values. Here is the step-by-step approach:

  1. Import the pandas library.
  2. Convert the list of tuples into a pandas DataFrame.
  3. Set the first element of each tuple as the index of the DataFrame.
  4. Filter the DataFrame based on the selection list.
  5. Calculate the summation of the values in the filtered DataFrame.
  6. Return the summation as the result.

Python3




# Python3 code to demonstrate
# Selective Records Value Summation
 
# importing pandas library
import pandas as pd
 
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
 
# initializing selection list
select_list = ['Nikhil', 'Akshat']
 
# printing original list
print("The original list is : " + str(test_list))
 
# printing selection list
print("The selection list is : " + str(select_list))
 
# convert the list of tuples to a pandas DataFrame
df = pd.DataFrame(test_list, columns=['key', 'value'])
 
# set the index of the DataFrame to the first element of each tuple
df.set_index('key', inplace=True)
 
# filter the DataFrame based on the selection list
df_filtered = df.loc[select_list]
 
# calculate the summation of the values in the filtered DataFrame
res = df_filtered['value'].sum()
 
# printing result
print("The selective values summation of keys : " + str(res))


OUTPUT:

The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values summation of keys : 4

Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(n), where n is the number of tuples in the list, due to the creation of the pandas DataFrame.

Method 7: reduce method from functools module:

Algorithm:

  1. Import the reduce function from the functools module.
  2. Define a list of tuples called test_list and a selection list called select_list.
  3. Define a variable called res to store the sum of values for the selected keys.
  4. Use the reduce function to iterate through each tuple in test_list and add the value to the res variable if the key is in the select_list.
  5. Print the value of the res variable.

Python3




from functools import reduce
 
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
select_list = ['Nikhil', 'Akshat']
 
# printing original list
print("The original list is : " + str(test_list))
  
# printing selection list
print("The selection list is : " + str(select_list))
  
res = reduce(lambda acc, x: acc + x[1] if x[0] in select_list else acc, test_list, 0)
 
# printing result
print("The selective values summation of keys : " + str(res))


Output

The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values summation of keys : 4

Time Complexity:
The time complexity of this code is O(n), where n is the number of tuples in the test_list. This is because the reduce function is used to iterate through each tuple in the test_list exactly once and check if a key in the select_list has a constant time complexity of O(1). Therefore, the time complexity of this code is linear in the size of the input.

Space Complexity:
The space complexity of this code is also O(n), where n is the number of tuples in the test_list. This is because the reduce function iterates through the test_list and stores each tuple in memory. Additionally, the res variable takes constant space in memory. Therefore, the space complexity of this code is linear in the size of the input.

Method 8: Using heapq:

Algorithm:

  1. Initialize the input list test_list and the select_list of selected keys.
  2. Print the original list test_list and select_list.
  3. Filter the input list test_list to keep only the elements whose key is present in the select_list using a list comprehension.
  4. Get the summation of the values of the selected elements using sum() function.
  5. Print the summation value as the output.

Python3




import heapq
 
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
select_list = ['Nikhil', 'Akshat']
 
# printing original list
print("The original list is : " + str(test_list))
 
# printing selection list
print("The selection list is : " + str(select_list))
 
# Filter the list to keep only the selected elements
filtered_list = [x for x in test_list if x[0] in select_list]
 
# Get the summation of values of the selected elements
res = sum(x[1] for x in filtered_list)
 
# printing result
print("The selective values summation of keys : " + str(res))
#This code is contributed by Rayudu.


Output

The original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values summation of keys : 4

Time Complexity: The time complexity of this algorithm is O(n), where n is the number of elements in the input list. The filtering of the elements takes linear time, and the summation of values takes constant time.

Space Complexity: The space complexity of this algorithm is O(k), where k is the number of elements in the filtered list. The filtered list can have at most k elements, so the space complexity is proportional to k.



Last Updated : 23 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads