Python|选择性记录值求和
有时,在使用元组列表时,我们会遇到一个问题,即我们有特定的键列表,我们只需要从元组列表中对这些键的值求和。这在对特定实体进行评级或求和方面具有实用性。让我们讨论一些可以做到这一点的方法。
方法 #1:使用dict() + sum() + get()
+ 列表理解
我们可以通过首先将列表转换为字典然后使用列表推导来使用 get函数获取特定键的值来执行此特定任务。使用 sum() 执行值的求和。
# 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))
输出 :
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
方法 #2:使用next() + sum()
+ 列表推导
这个特定问题可以使用下一个函数来解决,该函数使用迭代器执行迭代,因此可以更有效地实现可能的解决方案。使用 sum() 执行值的求和。
# 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))
输出 :
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