📜  Python|计算不匹配的元素

📅  最后修改于: 2022-05-13 01:54:45.513000             🧑  作者: Mango

Python|计算不匹配的元素

通过条件检查数字/元素是一个常见的问题,几乎在每个程序中都会遇到。有时我们还需要获取与特定条件不匹配的总数,以区分哪些匹配以供进一步使用。让我们讨论可以实现此任务的某些方法。

方法#1:使用循环
这是执行此特定任务的蛮力方法。在此,我们迭代列表,查找与特定条件不匹配的元素并进行计数。

Python3
# Python 3 code to demonstrate 
# Count unmatched elements
# 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
# Count unmatched elements
# checks for odd
res = 0
for ele in test_list:
    if not ele % 2 != 0:
        res = res + 1
           
# printing result
print ("The number of non-odd elements: " + str(res))


Python3
# Python 3 code to demonstrate 
# Count unmatched elements
# using len() + generator expression
   
# initializing list
test_list = [3, 5, 1, 6, 7, 9]
   
# printing original list
print ("The original list is : " + str(test_list))
   
# using len() + generator expression
# Count unmatched elements
# checks for odd
res = len(list(i for i in test_list if not i % 2 != 0))
   
# printing result
print ("The number of non-odd elements: " + str(res))


输出 :
The original list is : [3, 5, 1, 6, 7, 9]
The number of non-odd elements: 1

方法 #2:使用 len() + 生成器表达式
每当生成器表达式返回 False 时,此方法使用将元素计数到加 1 的技巧。当列表耗尽时,返回不匹配条件的数字计数。

Python3

# Python 3 code to demonstrate 
# Count unmatched elements
# using len() + generator expression
   
# initializing list
test_list = [3, 5, 1, 6, 7, 9]
   
# printing original list
print ("The original list is : " + str(test_list))
   
# using len() + generator expression
# Count unmatched elements
# checks for odd
res = len(list(i for i in test_list if not i % 2 != 0))
   
# printing result
print ("The number of non-odd elements: " + str(res))
输出 :
The original list is : [3, 5, 1, 6, 7, 9]
The number of non-odd elements: 1