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 - 使用迭代结构(while)的暴力方法
这里我们需要使用 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 < len(list1)):
# 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 < 0), list1)))
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
所有变量都在局部作用域中声明,并且它们的引用在上面的图中可见。
结论
在本文中,我们学习了如何在列表中计算正数和负数。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP