在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 < 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

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

结论

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