python中怎么表示正数_在Python程序的列表中计算正数和负数

在本文中,我们将学习下面给出的问题陈述的解决方案。

问题陈述-我们得到了一个可迭代的列表,我们需要计算其中的正数和负数并显示它们。

方法1:使用迭代构造的蛮力方法(for)

在这里,我们需要使用for循环迭代列表中的每个元素,并检查num> = 0是否过滤正数。如果条件评估为真,则增加pos_count,否则增加neg_count。

示例list1 = [1,-2,-4,6,7,-23,45,-0]

pos_count, neg_count = 0, 0

# enhanced for loop

for num in list1:

# check for being positive

if num >= 0:

pos_count += 1

else:

neg_count += 1

print("Positive numbers in the list: ", pos_count)

print("Negative numbers in the list: ", neg_count)

输出结果Positive numbers in the list: 5

Negative numbers in the list: 3

方法2:使用迭代构造的蛮力方法(同时)

在这里,我们需要使用for循环对列表中的每个元素进行迭代,并检查num> = 0,以过滤正数。如果条件评估为真,则增加pos_count,否则增加neg_count。

示例list1 = [1,-2,-4,6,7,-23,45,-0]

pos_count, neg_count = 0, 0

num = 0

# while loop

while(num 

# check

if list1[num] >= 0:

pos_count += 1

else:

neg_count += 1

# increment num

num += 1

print("Positive numbers in the list: ", pos_count)

print("Negative numbers in the list: ", neg_count)

输出结果Positive numbers in the list: 5

Negative numbers in the list: 3

方法3:使用Python Lambda表达式

在这里,我们借助filter和lambda表达式,可以直接区分正数和负数。

示例list1 = [1,-2,-4,6,7,-23,45,-0]

neg_count = len(list(filter(lambda x: (x 

pos_count = len(list(filter(lambda x: (x >= 0), list1)))

print("Positive numbers in the list: ", pos_count)

print("Negative numbers in the list: ", neg_count)

输出结果Positive numbers in the list: 5

Negative numbers in the list: 3

所有变量均在本地范围内声明,其引用如上图所示。

结论

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值