Python - 求和元素匹配条件
通过条件检查数字/元素是一个常见的问题,几乎在每个程序中都会遇到。有时我们还需要获取与特定条件匹配的总和,以区分哪些不匹配以供进一步使用。让我们讨论可以实现此任务的某些方法。
方法#1:使用循环
这是执行此特定任务的蛮力方法。在此,我们迭代列表,找到匹配特定条件的元素并求和。
Python3
# Python 3 code to demonstrate
# Sum elements matching condition
# using loop
# initializing list
test_list = [3, 5, 1, 6, 7, 9]
# printing original list
print ("The original list is : " + str(test_list))
# using loop
# Sum elements matching condition
# checks for odd
res = 0
for ele in test_list:
if ele % 2 != 0:
res = res + ele
# printing result
print ("The sum of odd elements: " + str(res))
Python3
# Python 3 code to demonstrate
# Sum elements matching condition
# using sum() + generator expression
# initializing list
test_list = [3, 5, 1, 6, 7, 9]
# printing original list
print ("The original list is : " + str(test_list))
# using sum() + generator expression
# Sum elements matching condition
# checks for odd
res = sum(i for i in test_list if i % 2 != 0)
# printing result
print ("The sum of odd elements: " + str(res))
输出 :
The original list is : [3, 5, 1, 6, 7, 9]
The sum of odd elements: 25
方法 #2:使用 sum() + 生成器表达式
只要生成器表达式返回 true,此方法就会使用将元素添加到总和的技巧。当列表耗尽时,返回匹配条件的数字的总和。
Python3
# Python 3 code to demonstrate
# Sum elements matching condition
# using sum() + generator expression
# initializing list
test_list = [3, 5, 1, 6, 7, 9]
# printing original list
print ("The original list is : " + str(test_list))
# using sum() + generator expression
# Sum elements matching condition
# checks for odd
res = sum(i for i in test_list if i % 2 != 0)
# printing result
print ("The sum of odd elements: " + str(res))
输出 :
The original list is : [3, 5, 1, 6, 7, 9]
The sum of odd elements: 25