Python程序可计算列表中的偶数和奇数
在本文中,我们将学习下面给出的问题陈述的解决方案。
问题陈述 -我们得到一个列表,我们需要计算列表中的偶数和奇数。
共有三种方法,如下-
方法1:使用蛮力方法
示例
list1 = [21,3,4,6,33,2,3,1,3,76]
even_count, odd_count = 0, 0
# enhanced for loop
for num in list1:
#even numbers
if num % 2 == 0:
even_count += 1
#odd numbers
else:
odd_count += 1
print("Even numbers available in the list: ", even_count)
print("Odd numbers available in the list: ", odd_count)输出结果
Even numbers available in the list: 4 Odd numbers available in the list: 6
方法2:使用filter()和lambda表达式
示例
list1 = [21,3,4,6,33,2,3,1,3,76]
#odd numbers
odd_count = len(list(filter(lambda x: (x%2 != 0) , list1)))
#even numbers
even_count = len(list(filter(lambda x: (x%2 == 0) , list1)))
print("Even numbers available in the list: ", even_count)
print("Odd numbers available in the list: ", odd_count)输出结果
Even numbers available in the list: 4 Odd numbers available in the list: 6
方法3:使用列表理解
示例
list1 = [21,3,4,6,33,2,3,1,3,76]
#copy of list elements which are odd in a new list and calculating
the length on new list
only_odd = [num for num in list1 if num % 2 == 1]
odd_count = len(only_odd)
print("Even numbers available in the list: ", len(list1) -
odd_count)
print("Odd numbers available in the list: ", odd_count)输出结果
Even numbers available in the list: 4 Odd numbers available in the list: 6
结论
在本文中,我们学习了如何计算列表中的偶数和奇数。
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短