给定一个数字列表, 编写一个Python程序以计算列表中的正数和负数。
例子:
Input: list1 = [2, -7, 5, -64, -14]
Output: pos = 2, neg = 3Input: list2 = [-12, 14, 95, 3]
Output: pos = 3, neg = 1
范例1:使用for循环计算给定列表中的正数和负数
使用for循环遍历列表中的每个元素, 并检查num> = 0, 这是检查正数的条件。如果条件满足, 则增加pos_count, 否则增加neg_count。
# Python program to count positive and negative numbers in a List# list of numbers
list1 = [ 10 , - 21 , 4 , - 45 , 66 , - 93 , 1 ]pos_count, neg_count = 0 , 0# iterating each number in list
for num in list1:# checking condition
if num >
= 0 :
pos_count + = 1else :
neg_count + = 1print ( "Positive numbers in the list: " , pos_count)
print ( "Negative numbers in the list: " , neg_count)
输出如下:
Positive numbers in the list:4
Negative numbers in the list:3
范例2:使用while循环
# Python program to count positive and negative numbers in a List# list of numbers
list1 = [ - 10 , - 21 , - 4 , - 45 , - 66 , 93 , 11 ]pos_count, neg_count = 0 , 0
num = 0# using while loop
while (num <
len (list1)):# checking condition
if list1[num] >
= 0 :
pos_count + = 1
else :
neg_count + = 1# increment num
num + = 1print ( "Positive numbers in the list: " , pos_count)
print ( "Negative numbers in the list: " , neg_count)
输出如下:
Positive numbers in the list:2
Negative numbers in the list:5
Example#3:使用Python Lambda表达式
# Python program to count positive
# and negative numbers in a List# list of numbers
list1 = [ 10 , - 21 , - 4 , 45 , 66 , 93 , - 11 ]neg_count = len ( list ( filter ( lambda x: (x <
0 ), list1)))# we can also do len(list1) - neg_count
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:4
Negative numbers in the list:3
【Python程序可计算列表中的正数和负数】Example#4:使用清单理解
# Python program to count positive
# and negative numbers in a List# list of numbers
list1 = [ - 10 , - 21 , - 4 , - 45 , - 66 , - 93 , 11 ]only_pos = [num for num in list1 if num >
= 1 ]
pos_count = len (only_pos)print ( "Positive numbers in the list: " , pos_count)
print ( "Negative numbers in the list: " , len (list1) - pos_count)
输出如下:
Positive numbers in the list:1
Negative numbers in the list:6
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。
推荐阅读
- JavaScript如何使用Date parse()方法(用法示例)
- jQuery如何使用多个ID选择器(代码示例)
- 检查给定字符串的字符是否可以重新排列以形成回文
- 算法设计(如何高效地找到数字的奇偶性())
- 了解基本的JavaScript代码,简要指南
- 进程表和进程控制块(PCB)详细指南
- 笔记本系统,本文教您华硕笔记本怎样运用U盘安装win8系统
- u盘插上电脑没反应,本文教您修好无法识别u盘问题
- 惠普电脑用U盘安装win7系统,本文教您U盘安装win7图文详细教程