Python程序:如何在列表中打印偶数?

2021年3月15日09:05:00 发表评论 951 次浏览

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

例子:

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

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

使用for循环:

使用for循环遍历列表中的每个元素, 并检查num%2 ==0。如果条件满足, 则仅打印数字。

# Python program to print Even Numbers in a List
  
# list of numbers
list1 = [ 10 , 21 , 4 , 45 , 66 , 93 ]
  
# iterating each number in list
for num in list1:
      
     # checking condition
     if num % 2 = = 0 :
        print (num, end = " " )

输出如下:

10, 4, 66

使用while循环

:

# Python program to print Even 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 num % 2 = = 0 :
        print (list1[num], end = " " )
      
     # increment num  
     num + = 1

输出如下:

10, 4, 66

使用列表理解

:

# Python program to print even Numbers in a List
  
# list of numbers
list1 = [ 10 , 21 , 4 , 45 , 66 , 93 ]
  
# using list comprehension
even_nos = [num for num in list1 if num % 2 = = 0 ]
  
print ( "Even numbers in the list: " , even_nos)

输出如下:

Even numbers in the list:  [10, 4, 66]

使用lambda表达式:

# Python program to print Even Numbers in a List
  
# list of numbers 
list1 = [ 10 , 21 , 4 , 45 , 66 , 93 , 11 ] 
  
  
# we can also print even no's using lambda exp. 
even_nos = list ( filter ( lambda x: (x % 2 = = 0 ), list1))
  
print ( "Even numbers in the list: " , even_nos)

输出如下:

Even numbers in the list:  [10, 4, 66]

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


木子山

发表评论

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