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

2021年3月19日18:25:11 发表评论 755 次浏览

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

例子:

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

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

使用for循环:

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

# Python program to print odd 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 = " " )

输出如下:

21 45 93

使用while循环

:

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

输出如下:

21 45 93

使用列表理解

:

# Python program to print odd Numbers in a List
  
# list of numbers
list1 = [ 10 , 21 , 4 , 45 , 66 , 93 ]
  
only_odd = [num for num in list1 if num % 2 = = 1 ]
  
print (only_odd)

输出如下:

21 45 93

使用lambda表达式:

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

输出如下:

Odd numbers in the list:  [21, 45, 93, 11]

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

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


木子山

发表评论

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