Python程序如何实现在列表中打印正数?

2021年3月19日18:22:29 发表评论 630 次浏览

给定一个数字列表, 编写一个Python程序以打印给定列表中的所有正数。

例子:

Input: list1 = [12, -7, 5, 64, -14]
Output: 12, 5, 64

Input: list2 = [12, 14, -95, 3]
Output: [12, 14, 3]

范例1:使用for循环打印给定列表中的所有正数

使用for循环遍历列表中的每个元素, 并检查number是否大于或等于0。如果条件满足, 则仅打印该数字。

# Python program to print positive Numbers in a List
  
# list of numbers
list1 = [ 11 , - 21 , 0 , 45 , 66 , - 93 ]
  
# iterating each number in list
for num in list1:
      
     # checking condition
     if num > = 0 :
        print (num, end = " " )

输出如下:

11 0 45 66

范例2:

使用while循环

# Python program to print positive Numbers in a List
  
# list of numbers
list1 = [ - 10 , 21 , - 4 , - 45 , - 66 , 93 ]
num = 0
  
# using while loop     
while (num < len (list1)):
      
     # checking condition
     if list1[num] > = 0 :
         print (list1[num], end = " " )
      
     # increment num 
     num + = 1

输出如下:

21 93

范例3:

使用

清单理解

# Python program to print Positive Numbers in a List
  
# list of numbers
list1 = [ - 10 , - 21 , - 4 , 45 , - 66 , 93 ]
  
# using list comprehension
pos_nos = [num for num in list1 if num > = 0 ]
  
print ( "Positive numbers in the list: " , * pos_nos)

输出如下:

Positive numbers in the list:  45 93

范例4:

使用

Lambda表达式

# Python program to print positive Numbers in a List
  
# list of numbers 
list1 = [ - 10 , 21 , 4 , - 45 , - 66 , 93 , - 11 ] 
  
  
# we can also print positive no's using lambda exp. 
pos_nos = list ( filter ( lambda x: (x > = 0 ), list1))
  
print ( "Positive numbers in the list: " , * pos_nos)

输出如下:

Positive numbers in the list:  21, 4, 93

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: