Python程序(如何在列表中打印偶数())

给定一个数字列表, 编写一个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 = " " )

【Python程序(如何在列表中打印偶数())】输出如下:
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课程。

    推荐阅读