python中偶数怎么表示_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

结论

在本文中,我们学习了如何计算列表中的偶数和奇数。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值